How to detect if browser supports HTML5 Local Storage

JavascriptHtml

Javascript Problem Overview


The following code alerts ls exist in IE7:

if(window.localStorage) {
	alert('ls exists');
} else {
	alert('ls does not exist');
}

IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?

Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.

Javascript Solutions


Solution 1 - Javascript

You don't have to use modernizr, but you can use their method to detect if localStorage is supported

modernizr at github
test for localStorage

// In FF4, if disabled, window.localStorage should === null.

// Normally, we could not test that directly and need to do a
//   `('localStorage' in window) && ` test first because otherwise Firefox will
//   throw bugzil.la/365772 if cookies are disabled

// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
//   QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.

// Because we are forced to try/catch this, we'll go aggressive.

// Just FWIW: IE8 Compat mode supports these features completely:
//   www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files

Modernizr.addTest('localstorage', function() {
    var mod = 'modernizr';
    try {
        localStorage.setItem(mod, mod);
        localStorage.removeItem(mod);
        return true;
    } catch(e) {
        return false;
    }
});

updated with current source code

Solution 2 - Javascript

if(typeof Storage !== "undefined")
  {
  // Yes! localStorage and sessionStorage support!
  // Some code.....
  }
else
  {
  // Sorry! No web storage support..
  }

Solution 3 - Javascript

This function works fine:

function supports_html5_storage(){
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch(e) {
        return false;
    }
}

Source: www.diveintohtml5.info

Solution 4 - Javascript

> Also I don't want to use Modernizr since I am using only a few HTML5 > features and loading a large script isn't worth it just to detect > support for those few things.

To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.

Solution 5 - Javascript

Try window.localStorage!==undefined:

if(window.localStorage!==undefined){
    //Do something
}else{
    alert('Your browser is outdated!');
}

You can also use typeof window.localStorage!=="undefined", but the statement above already does it

Solution 6 - Javascript

I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.

If you use jQuery, you can do:

var _supportsLocalStorage = !!window.localStorage
    && $.isFunction(localStorage.getItem)
    && $.isFunction(localStorage.setItem)
    && $.isFunction(localStorage.removeItem);

Or, with pure Vanilla JavaScript:

var _supportsLocalStorage = !!window.localStorage
    && typeof localStorage.getItem === 'function'
    && typeof localStorage.setItem === 'function'
    && typeof localStorage.removeItem === 'function';

Then, you would simply do an IF to test the support:

if (_supportsLocalStorage) {
    console.log('ls is supported');
    alert('ls is supported');
}

So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.

Solution 7 - Javascript

Try catch will do the job :

    try{
       localStorage.setItem("name",name.value);
       localStorage.setItem("post",post.value);
       }
    catch(e){
       alert(e.message);    
       }

Solution 8 - Javascript

Try:

if(typeof window.localStorage != 'undefined') {
}

Solution 9 - Javascript

if (window.localStorage){
	
   alert('localStorage is supported');
   window.localStorage.setItem("whatever", "string value");

}

Solution 10 - Javascript

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

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

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

function script(){
  if(ls){
    alert('Yes');
  } else {
    alert('No');
  }
}

<button onclick="script()">Local Storage Support?</button>

Solution 11 - Javascript

I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.

> Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.

So without further ado here is my code:

/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */

if (typeof isSessStorageAllowed !== 'function')
	{
		function isSessStorageAllowed()
			{
				if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
					{
						try
							{
								var cur_dt = new Date();
								var cur_tm = cur_dt.getTime();
								var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
								var ss_test_val = 'ss_test_val_' + String(cur_tm);

								sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));

								if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
									{
										return true;
									}
								else
									{
										return false;
									};

								sessionStorage.removeItem(ss_test_itm_key);
							}
						catch (exception)
							{
								return false;
							};
					}
				else
					{
						return false;
					};
			};
	};

/* Conditional Function checks a web browser for 'session storage' support. [END] */

/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */

if (typeof isLclStorageAllowed !== 'function')
	{
		function isLclStorageAllowed()
			{
				if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
					{
						try
							{
								var cur_dt = new Date();
								var cur_tm = cur_dt.getTime();
								var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
								var ls_test_val = 'ls_test_val_' + String(cur_tm);

								localStorage.setItem(ls_test_itm_key, String(ls_test_val));

								if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
									{
										return true;
									}
								else
									{
										return false;
									};

								localStorage.removeItem(ls_test_itm_key);
							}
						catch (exception)
							{
								return false;
							};
					}
				else
					{
						return false;
					};
			};
	};

/* Conditional Function checks a web browser for 'local storage' support. [END] */

/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */

/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */

if (typeof isWebStorageAllowed !== 'function')
	{
		function isWebStorageAllowed()
			{
				if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
					{
						return true;
					}
				else
					{
						return false;
					};
			};
	};

/* Conditional Function checks a web browser for 'web storage' support. [END] */

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
Questionuser967451View Question on Stackoverflow
Solution 1 - JavascriptAndreasView Answer on Stackoverflow
Solution 2 - JavascriptBrandon FerraraView Answer on Stackoverflow
Solution 3 - JavascriptjuanraView Answer on Stackoverflow
Solution 4 - JavascriptSteve AView Answer on Stackoverflow
Solution 5 - JavascriptDanilo ValenteView Answer on Stackoverflow
Solution 6 - JavascriptOvi TrifView Answer on Stackoverflow
Solution 7 - JavascriptMohit VermaView Answer on Stackoverflow
Solution 8 - JavascriptErJabView Answer on Stackoverflow
Solution 9 - JavascriptDarrenView Answer on Stackoverflow
Solution 10 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 11 - JavascriptJames Anderson Jr.View Answer on Stackoverflow