Skip to content

Instantly share code, notes, and snippets.

@beaulac
Created July 5, 2017 22:35
Show Gist options
  • Save beaulac/e4c7fe3c46f6108fc9c7116a4c583056 to your computer and use it in GitHub Desktop.
Save beaulac/e4c7fe3c46f6108fc9c7116a4c583056 to your computer and use it in GitHub Desktop.
Proper checking of storage type
function StorageConfig(storeProvider) {
storeProvider.setStore(_determineStoreType());
function _determineStoreType() {
if ((typeof localStorage === 'object') && _checkStorage(localStorage)) {
return 'localStorage';
} else if ((typeof sessionStorage === 'object') && _checkStorage(sessionStorage)) {
return 'sessionStorage';
} else {
return 'cookieStorage';
}
function _checkStorage(storage) {
var isStorageAvailable = false,
testValue = Math.random().toString(36).slice(2);
try {
storage.setItem(testValue, testValue);
isStorageAvailable = (storage.getItem(testValue) === testValue);
} catch (_) {
isStorageAvailable = false;
} finally {
try {
storage.removeItem(testValue);
} catch (_) {
isStorageAvailable = false;
}
}
return isStorageAvailable;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment