user967451
user967451

Reputation:

How to detect if browser supports HTML5 Local Storage

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.

Upvotes: 90

Views: 89914

Answers (11)

James Anderson Jr.
James Anderson Jr.

Reputation: 806

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] */

Upvotes: 0

Ronnie Smith
Ronnie Smith

Reputation: 18565

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>

Upvotes: 1

Ovi Trif
Ovi Trif

Reputation: 401

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.

Upvotes: 8

Steve A
Steve A

Reputation: 151

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.

Upvotes: 15

Brandon Ferrara
Brandon Ferrara

Reputation: 1388

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

Upvotes: 46

Andreas
Andreas

Reputation: 21881

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

Upvotes: 101

juanra
juanra

Reputation: 1642

This function works fine:

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

Source: www.diveintohtml5.info

Upvotes: 18

Darren
Darren

Reputation: 19

if (window.localStorage){

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

}

Upvotes: 1

Mohit Verma
Mohit Verma

Reputation: 1660

Try catch will do the job :

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

Upvotes: 3

ErJab
ErJab

Reputation: 6375

Try:

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

Upvotes: 1

Danilo Valente
Danilo Valente

Reputation: 11342

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

Upvotes: 10

Related Questions