Hidde
Hidde

Reputation: 11961

Check for HTML 5 localStorage

How to check for HTML 5 localStorage compability of the users browser?

I have been using two checks:

    if (window.localStorage) {
       // localStorage works!
    }

and

    if (typeof(localStorage) != 'undefined') {
         // localStorage works!
    }

Also, I have seen a function online which uses an try/catch block to check whether localStorage can add a key/data pair, or throws an error.

Which of those three methods would you recommend, and are there any differences between the first and the second?

Upvotes: 4

Views: 2608

Answers (3)

Sirko
Sirko

Reputation: 74086

The following is the code Modernizr (code) uses for localstorage

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

IMO this is pretty much the recommended way to check for it.

Upvotes: 3

Marat Tanalin
Marat Tanalin

Reputation: 14123

Both are equivalent here. First is shorter and therefore more convenient. This method is used, for example, in MDN code for adding localStorage imitation that uses cookies.

Upvotes: 0

user123444555621
user123444555621

Reputation: 153234

@MathiasBynens has written a nice article about this, comparing different approaches:

http://mathiasbynens.be/notes/localstorage-pattern

Upvotes: 2

Related Questions