Checking if localStorage is available in JS

Update: In April 2017 Apple has changed this behaviour, so this post is now obsolete.

localStorage is a great feature supported by all modern browsers and even IE 8+, but before using it in your code you should make sure it is available in the browser.

On the internet you can find solutions that look very comprehensive:

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

But using this code is dangerous. Let's take a look at an example:

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

// save the data if localStorage is available
if (_supportsLocalStorage) {
    localStorage.setItem('foo', 'bar'); // this line gives an error in Private Tab in Safari
}

// continues with important code...

If we run this code in Private Tab in Safari, it will give us an error when setting a localStorage item, so all the important code after that will not run. That means that your website might very well be completely broken in Private Tab in Safari, and if you are working on your own small project you might not even know this is happening, especially if you are not developing on MacOS.

This happens because the solution above only checks if the functions exist, and in Safari in Private Tab these functions do exist, but do not work. Probably to make sure you can't be tracked.

Here is a function that covers this case:

function localStorageAvailable() {
    // if window.localStorage is not defined, return false right away
    if (window.localStorage) {
        var test = "__localStorageTest__";

        // try to use localStorage, and if it does not give any error, then it is available
        try {
            window.localStorage.setItem(test, test);
            window.localStorage.removeItem(test);
        } catch (ex) {
            return false;
        }

        return true;
    }

    return false;
};

It returns true if localStorage is available and ready to use, and false if it is

  • not supported, or
  • not allowed to be used, or
  • has no space left

If you do not plan to use localStorage extensively (storing a couple of megabytes worth of information there) this is good enough. But if you do, you've got another problem, which I will talk about next time.

Big takeaway: testing your website in all the browsers is not enough, you need to test them in private mods as well

2017  
1 comment
makkkes

Wow, finally you've got a blog in English, awesome! :)