Although localStorage
API is available in current versions of all major browsers, the user may still encounter the exception Failed to read the 'localStorage'
for localStorate
has been disabled in browser settings. Like on Chrome, the user can check “Block cookies” option in the privacy settings to make localStorage
is blocked too.
Therefore it is necessary to detect the availability of localStorage
to fix the issue.
Uncaught DOMException: Failed to read the ‘localStorage’ property from ‘Window’
The full error message is:
Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
Solution
MDN provides a a function that detects whether localStorage
is both supported and available:
function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}
Then you access localStorage
only if it is available.
let isStorageAvailable = storageAvailable();
if (isStorageAvailable) {
// Access localStorage
}
Further reading
- JavaScript storage
This post introduces modern Web data storage like sessionStorage, localStorage, IndexedDB, Cache, etc, as well as their applicable scenarios.