dscheerens / ngx-webstorage-service

Module for Angular that provides service wrappers for the Web Storage API
MIT License
65 stars 11 forks source link

Fallback not working #8

Closed szechyjs closed 5 years ago

szechyjs commented 5 years ago

I've disabled localstorage in Chrome to test the fallback, however it is not working.

ERROR Error: Uncaught (in promise): SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
Error: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
    at localStorageFactory (ngx-webstorage-service.js:185)

ngx-webstorage-service.js:185 maps to -> https://github.com/dscheerens/ngx-webstorage-service/blob/master/lib/src/storage-service.module.ts#L22

A similar error occurs for session storage.

ERROR Error: Uncaught (in promise): SecurityError: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.
Error: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.
    at sessionStorageFactory (ngx-webstorage-service.js:179)

ngx-webstorage-service.js:179 maps to -> https://github.com/dscheerens/ngx-webstorage-service/blob/master/lib/src/storage-service.module.ts#L14

This is how modernizr detects availability: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Seems a try/catch is the only way to properly do this, as browsers like Chrome throw an exception when trying to access localStorage and sessionStorage.

dscheerens commented 5 years ago

Ah, thanks for reporting this. The fallback is working in some cases (Safari in private mode), but I haven't actually seen this case. I'll try to release a patch later today

szechyjs commented 5 years ago

Looking at the implementation of isStorageAvailable it looks like it's doing something similar to modernizr. The solution may just be to remove the checks for undefined, as they are what throw the exceptions (and not being caught).

typeof sessionStorage as any === 'undefined'

dscheerens commented 5 years ago

Those are actually necessary when the module is used in a NodeJS environment (e.g. when using Angular Universal).

dscheerens commented 5 years ago

@szechyjs Should be fixed in version 3.1.2. Thanks again for reporting the issue! :+1:

dscheerens commented 5 years ago

Oops, I messed up the condition :(

Fixed in version 3.1.3