Created
July 5, 2017 22:35
-
-
Save beaulac/e4c7fe3c46f6108fc9c7116a4c583056 to your computer and use it in GitHub Desktop.
Proper checking of storage type
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
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