HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Check if localStorage or sessionStorage is enabled

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptchecksessionstorageenabledlocalstorage

Problem

Working with 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 accessible


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.
> [!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 accessible
const 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 accessible

Context

From 30-seconds-of-code: is-local-storage-session-storage-enabled

Revisions (0)

No revisions yet.