Check if localStorage is available

JavascriptError HandlingLocal Storage

Javascript Problem Overview


I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here's the code I'm using to check:

localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
  alert ('yes');
  localStorage.removeItem('mod');
} else {
  alert ('no');
}

Simple function and it works. But if I go into my Chrome settings and choose the option "Don't Save Data" (I don't remember exactly what it's called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?

UPDATE: This is the second function I tried and I still get no response (alert).

try {
  localStorage.setItem('name', 'Hello World!');
} catch (e) {
  if (e == QUOTA_EXCEEDED_ERR) {
   alert('Quota exceeded!');
  }
}

Javascript Solutions


Solution 1 - Javascript

Use modernizr's approach (you might want to change my function name to something better):

function lsTest(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

if(lsTest() === true){
    // available
}else{
    // unavailable
}

It's not as concise as other methods but that's because it's designed to maximise compatibility.

The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Working example: http://jsfiddle.net/6sm54/2/

Solution 2 - Javascript

I'd check that localStorage is defined prior to any action that depends on it:

if (typeof localStorage !== 'undefined') {
    var x = localStorage.getItem('mod');
} else {
    // localStorage not defined
}

UPDATE:

If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:

if (typeof localStorage !== 'undefined') {
    try {
        localStorage.setItem('feature_test', 'yes');
        if (localStorage.getItem('feature_test') === 'yes') {
            localStorage.removeItem('feature_test');
            // localStorage is enabled
        } else {
            // localStorage is disabled
        }
    } catch(e) {
        // localStorage is disabled
    }
} else {
    // localStorage is not available
}

Solution 3 - Javascript

Feature-detecting local storage is tricky. You need to actually reach into it. The reason for this is that Safari has chosen to offer a functional localStorage object when in private mode, but with it's quotum set to zero. This means that although all simple feature detects will pass, any calls to localStorage.setItem will throw an exception.

Mozilla's Developer Network entry on the Web Storage API's has a dedicated section on feature detecting local storage. Here is the method recommended on that page:

function storageAvailable(type) {
	try {
		var storage = window[type],
			x = '__storage_test__';
		storage.setItem(x, x);
		storage.removeItem(x);
		return true;
	}
	catch(e) {
		return false;
	}
}

And here is how you would use it:

if (storageAvailable('localStorage')) {
	// Yippee! We can use localStorage awesomeness
}
else {
	// Too bad, no localStorage for us
}

If you are using NPM, you can grab storage-available using

npm install -S storage-available

then use the function like so:

if (require('storage-available')('localStorage')) {
    // Yippee! We can use localStorage awesomeness
}

Disclaimer: Both the documentation section on MDN and the NPM package were authored by me.

Solution 4 - Javascript

MDN updated the storage detect function. In 2018, it's more reliable:

function storageAvailable() {
    try {
        var storage = window['localStorage'],
            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;
    }
}

> Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may support localStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.

> See here for a brief history of feature-detecting localStorage.

Solution 5 - Javascript

With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.

function isLocalStorageAvailable() {

    try {
        var valueToStore = 'test';
        var mykey = 'key';
        localStorage.setItem(mykey, valueToStore);
        var recoveredValue = localStorage.getItem(mykey);
        localStorage.removeItem(mykey);

        return recoveredValue === valueToStore;
    } catch(e) {
        return false;
    }
}

Solution 6 - Javascript

You can try this method Anytime validate the content of the localstore

const name = localStorage.getItem('name');
if(name){
    console.log('Exists');
}else
{
    console.log('Not found');
}

Solution 7 - Javascript

Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...

Object.defineProperty(this, "ls", {
  get: function () { 
    var test = 'test';
    try {
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch(e) {
      return false;
    }
  }
});

Solution 8 - Javascript

It is better to check availability of localStorage in conjunction with cookies, because if cookie is enabled the browser could detect that localStorage is available and type it as object, but provide no possibility to work with it. You use the next function to detect both localStorage and cookies:

const isLocalStorage = () => {
  try {
    if (typeof localStorage === 'object' && navigator.cookieEnabled) return true
    else return false
  } catch (e) {
    return false
  }
}

Solution 9 - Javascript

Here is an easy check:

if(typeof localStorage === 'undefined'){

Solution 10 - Javascript

Use this to check localStorage is set or not. Its help you to get status of Localstorage.

    if( window.localStorage.fullName !== undefined){
          
           //action
   }else{
          }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2025469View Question on Stackoverflow
Solution 1 - JavascriptJoeView Answer on Stackoverflow
Solution 2 - JavascriptFrederik.LView Answer on Stackoverflow
Solution 3 - JavascriptStijn de WittView Answer on Stackoverflow
Solution 4 - JavascriptmcmimikView Answer on Stackoverflow
Solution 5 - Javascriptluis moyanoView Answer on Stackoverflow
Solution 6 - JavascriptShortys Oberto DutariView Answer on Stackoverflow
Solution 7 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 8 - JavascriptRuslan KorkinView Answer on Stackoverflow
Solution 9 - JavascriptBradyView Answer on Stackoverflow
Solution 10 - JavascriptLucky WView Answer on Stackoverflow