Last active
May 30, 2020 15:40
-
-
Save jherax/479d1889b44234b79b23 to your computer and use it in GitHub Desktop.
Detect availability of Web Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tests availability of global objects | |
// that implement Web Storage interface | |
if (storageAvailable('localStorage')) { | |
// you can use Web Storage | |
} | |
else { | |
// private mode or unavailable | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: