Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if browser supports localStorage #19

Open
MyXoToD opened this issue Apr 16, 2015 · 2 comments
Open

Check if browser supports localStorage #19

MyXoToD opened this issue Apr 16, 2015 · 2 comments

Comments

@MyXoToD
Copy link
Member

MyXoToD commented Apr 16, 2015

very very very important!

@MyXoToD
Copy link
Member Author

MyXoToD commented Apr 16, 2015

Looks like there's no reliable method out there. Need more research.

@KevinGimbel
Copy link

You can check for localStorage with a one-liner like

var hasLocalStorage = !!(window.localStorage);

The !! turns whatever window.localStorage returns into a boolean, kind of like (bool) $myVar in PHP.

This should work in most cases, anyway you may want to check if localStorage is native or not, so the whole script might look like this:

var hasLocalStorage = (function(window, document, undefined) {
  var hasStorage = window.localStorage;
  var isNative;
  // when there's nothing assigned to window.localStorage
  // return false because there's no localStorage
  if(!hasStorage) {
    return false;
  }

  // This code only gets executed when the above is true, so localStorage is supported
  // Native window.localStorage returns "[object Storage]" when toString() is used
  // the indexOf('[object Storage]') > -1 returns true if "[object Storage]" is found and
  // false if not. 
  isNative = window.localStorage.toString().indexOf('[object Storage]') > -1;
  if(isNative) {
    return true;
  } else {
    // handle non-native implementation? Maybe return -1 or whatever.
   return -1;
  }
}(window, document));

// Example

if(hasLocalStorage > -1) {
 // SUPPORTED \o/
} else {
 window.localStorage = function() { ... }
}

http://codepen.io/kevingimbel/pen/OyVyQW/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants