snippetjavascriptTip
Check if localStorage or sessionStorage is enabled
Viewed 0 times
javascriptchecksessionstorageenabledlocalstorage
Problem
Working with
In any case, it is always a good idea to check if
Checking if
Using
Checking if
localStorage and sessionStorage often poses challenges, the most significant of which is that they are not always available. This may be due to the browser's security settings, or the user's privacy settings, or even the browser's version.In any case, it is always a good idea to check if
localStorage or sessionStorage is available before using it.Checking if
localStorage is enabled requires some trial and error, quite literally, as we will use a try...catch block to test if operations in localStorage are supported.Using
Storage.setItem() and Storage.removeItem() we will try to store and delete a value in localStorage. If both operations complete successfully, we will return true, otherwise we will return false.Checking if
sessionStorage is enabled is the exact same as checking if localStorage is enabled, except that we will use sessionStorage instead of localStorage.Solution
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 accessibleChecking if
localStorage is enabled requires some trial and error, quite literally, as we will use a try...catch block to test if operations in localStorage are supported.Using
Storage.setItem() and Storage.removeItem() we will try to store and delete a value in localStorage. If both operations complete successfully, we will return true, otherwise we will return false.Checking if
sessionStorage is enabled is the exact same as checking if localStorage is enabled, except that we will use sessionStorage instead of localStorage.> [!TIP]
>
> You can learn about the differences between
localStorage and sessionStorage in a previous article.Code Snippets
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 accessibleconst isSessionStorageEnabled = () => {
try {
const key = `__storage__test`;
window.sessionStorage.setItem(key, null);
window.sessionStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
};
isSessionStorageEnabled(); // true, if sessionStorage is accessibleContext
From 30-seconds-of-code: is-local-storage-session-storage-enabled
Revisions (0)
No revisions yet.