Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:40
Show Gist options
  • Save jherax/479d1889b44234b79b23 to your computer and use it in GitHub Desktop.
Save jherax/479d1889b44234b79b23 to your computer and use it in GitHub Desktop.
Detect availability of Web Storage
/**
* Checks whether a storage mechanism is available.
* @param {String} storageType: it can be "localStorage", "sessionStorage" or any global object that implements Web Storage interface.
* @return {Boolean}
*/
function storageAvailable(storageType) {
var storage = window[storageType];
var data = '__proxy-storage__';
try {
storage.setItem(data, data);
storage.removeItem(data);
return true;
}
catch(e) {
return false;
}
}
// tests availability of global objects
// that implement Web Storage interface
if (storageAvailable('localStorage')) {
// you can use Web Storage
}
else {
// private mode or unavailable
}
@Download
Copy link

If you want to be able to treat all cases the same, whether storage is actually available or not, you can shim the local storage API by using a polyfill. I can recommend memorystorage as it's written by a very friendly author ;)

For example:

//Web Storage aliases
var _localStorage = storageAvailable('localStorage') ? window.localStorage : new MemoryStorage('local');
// from here on, _localStorage will just work, whether it's actually available or not. 
// However data will be gone as soon as the page is refreshed.

@jherax
Copy link
Author

jherax commented Oct 10, 2016

@Download Thank you for your feed back!

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