90

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.

falsarella
  • 12,217
  • 9
  • 69
  • 115
  • Possible duplicate of [Check for HTML 5 localStorage](https://stackoverflow.com/questions/9535530/check-for-html-5-localstorage) – BuZZ-dEE Nov 02 '17 at 13:17

11 Answers11

101

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

Endless
  • 34,080
  • 13
  • 108
  • 131
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 3
    Add `var mod = "test";` before the try-catch block, otherwise this will always fail since mod is undefined there. – Mahn Aug 17 '13 at 16:24
  • You're right. I'd just copied the source from modernizr and relied on the correctness of it... – Andreas Aug 17 '13 at 19:09
  • 6
    this might fail if there is no space in the localstorage left. – Patrick Jan 07 '16 at 15:33
  • 1
    Honestly, this isn't the best test because what if the local storage is just full? localStorage can be supported, but just in a state where you can't add. – DemiImp Nov 16 '16 at 20:01
  • 2
    Note, this will fire storage events in other windows – Mark Swardstrom Oct 19 '17 at 21:30
  • @Swards That's how it is supposed to work. [StorageEvent](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent): _"A `StorageEvent` is sent to a window when a storage area it has access to is changed within the context of another document."_; [Specification](https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-event); [Responding to storage changes with the StorageEvent](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent) – Andreas Oct 20 '17 at 06:19
  • 2
    @Andreas - Yes, I know. This test modifies the local storage. If you don't want that to happen and just want to test for support, other solutions might be a better choice. – Mark Swardstrom Oct 20 '17 at 06:28
  • See also https://michalzalecki.com/why-using-localStorage-directly-is-a-bad-idea/ – Yves M. Nov 28 '22 at 13:21
46
if(typeof Storage !== "undefined")
  {
  // Yes! localStorage and sessionStorage support!
  // Some code.....
  }
else
  {
  // Sorry! No web storage support..
  }
Parixit
  • 3,829
  • 3
  • 37
  • 61
Brandon Ferrara
  • 1,358
  • 9
  • 3
18

This function works fine:

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

Source: www.diveintohtml5.info

juanra
  • 1,602
  • 19
  • 17
  • 1
    It past a long time. and I know, it's the best answer since I read the book. By my question is why we are checking one thing twice to be NULL ? – Ali Saberi Aug 21 '16 at 14:47
  • I think the first `'localStorage' in window` checks that the property exists in the window object (is not 'undefined'), and the second `window['localStorage'] !== null` checks that that property is not NULL. – juanra Aug 23 '16 at 06:14
  • 1
    Couldn't that be achived by simply doing a non-strict equality check of window['localStorage'] == null? That covers both the undefined and the null check. – Triynko Sep 30 '16 at 15:08
  • Well, I guess so. If you check ´window['something'] == null´, the result is "true", even when it's undefined. Nonetheless I would choose the first method for the clarity sake. – juanra Oct 03 '16 at 13:58
15

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.

falsarella
  • 12,217
  • 9
  • 69
  • 115
Steve A
  • 151
  • 1
  • 4
  • 4
    Hi, welcome to Stack Overflow! This really sounds more like it should be a [comment](http://stackoverflow.com/privileges/comment) rather than an *answer* to the original question. I realize you can't comment yet, but reaching 50 [rep](http://stackoverflow.com/faq#reputation) isn't hard or time consuming. – Jesse Apr 01 '13 at 14:33
  • 1
    you can do it - only 9 more rep to go! ok I upvoted so now you have 51 – Simon_Weaver Apr 28 '15 at 02:56
  • I realize 1.55kb is nothing, but it still seems like overkill just to check localStorage support. – Tyler Biscoe Feb 08 '17 at 16:44
11

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

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • 2
    Safari may have localStorage but cast an error if in private mode (QuotaExceededError) so tr/catch is the best option IMHO – Endless Dec 04 '14 at 17:05
  • 1
    Hm, I didn't know that. But it only throws that error when trying to write stuff, right? – Danilo Valente Dec 04 '14 at 18:33
  • 1
    Actually the mere checking of the window.localStorage attribute (like shown in this example) will throw an error when Safari is set up to block cookies and website data. Specifically: `SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.` – Aaronius Jun 03 '15 at 16:52
  • Private browsing mode in Safari doesn't support writing to localStorage, but this check returns true for that case. The solution by Andreas handles this case. – Deepak Joy Cheenath Oct 06 '16 at 13:25
8

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.

Ovi Trif
  • 394
  • 4
  • 11
3

Try catch will do the job :

    try{
       localStorage.setItem("name",name.value);
       localStorage.setItem("post",post.value);
       }
    catch(e){
       alert(e.message);    
       }
Mohit Verma
  • 1,620
  • 2
  • 20
  • 30
1

Try:

if(typeof window.localStorage != 'undefined') {
}
ErJab
  • 6,056
  • 10
  • 42
  • 54
1
if (window.localStorage){

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

}
Thirumalai murugan
  • 5,698
  • 8
  • 32
  • 54
Darren
  • 19
  • 1
1

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>
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

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] */
James Anderson Jr.
  • 760
  • 1
  • 8
  • 26