gsklee / ngStorage

localStorage and sessionStorage done right for AngularJS.
MIT License
2.33k stars 461 forks source link

Uncaught SyntaxError: Unexpected token _ in JSON at position 0 #260

Open eaidland opened 7 years ago

eaidland commented 7 years ago

Hi! Got alot of error messages in console when using this module: Uncaught SyntaxError: Unexpected token _ in JSON at position 0(…) ngStorage.js:220

event.newValue ? $storage[event.key.slice(prefixLength)] = deserializer(event.newValue) : delete $storage[event.key.slice(prefixLength)];

Changed to

event.newValue && !angular.isUndefined($storage[event.key.slice(prefixLength)]) ? $storage[event.key.slice(prefixLength)] = deserializer(event.newValue) : delete $storage[event.key.slice(prefixLength)];

Now there's no error messages :)

kutu commented 7 years ago

i have this issue too i use angular and iframes on one page, and all pages use local storage, and this error always happens there is some event come from angular into ngstorage and its value starts with _

untitled

but if its just one app page with no iframes, everything is fine

floriangosse commented 7 years ago

I have the same problem and I think that's because some parts of the application don't store JSON serialized values in the localStorage and ngStorage tries to deserialize every value as JSON (https://github.com/gsklee/ngStorage/blob/843d78ec719410850d0df136307189a5a3c07f7a/ngStorage.js#L117).

I think you could try to set your own deserializer which catches these errors:

var deserializer = function (value) {
    try {
        return JSON.parse(value);
    } catch (err) {
        // We expect that the error is a JSON parsing error.
        return value;
    }
};