Check if localStorage is enabled
JavaScript, Browser · Dec 31, 2020

Checks if localStorage
is enabled.
- Use a
try...catch
block to returntrue
if all operations complete successfully,false
otherwise. - Use
Storage.setItem()
andStorage.removeItem()
to test storing and deleting a value inWindow.localStorage
.
const isLocalStorageEnabled = () => {
try {
const key = `__storage__test`;
window.localStorage.setItem(key, null);
window.localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
};
isLocalStorageEnabled(); // true, if localStorage is accessible
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.