Last active
March 21, 2019 11:21
-
-
Save dominictobias/e078402b9d0264dd169f21dd246ec890 to your computer and use it in GitHub Desktop.
Simple local and session storage wrapper - falls back to memory in the case of Safari Private browser
This file contains hidden or 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 isAvailable() { | |
try { | |
this.storage.setItem('__testFeature', true); | |
this.storage.removeItem('__testFeature'); | |
return true; | |
} catch (ex) { | |
return false; | |
} | |
} | |
class Storage { | |
constructor(type) { | |
this.storage = window[type]; | |
this.backupStorage = {}; | |
this.isAvailable = isAvailable(); | |
} | |
get(key, defaultValue) { | |
if (!this.isAvailable) { | |
return this.backupStorage[key] !== undefined ? | |
this.backupStorage[key] : defaultValue; | |
} | |
try { | |
const storageData = JSON.parse(this.storage.getItem(key)); | |
return storageData !== null ? storageData : defaultValue; | |
} catch (ex) { | |
// eslint-disable-next-line no-console | |
console.warn(`Unable to parse storage value ${key}`); | |
return defaultValue; | |
} | |
} | |
set(key, value) { | |
if (!this.isAvailable) { | |
this.backupStorage[key] = value; | |
return; | |
} | |
this.storage.setItem(key, JSON.stringify(value)); | |
} | |
remove(key) { | |
if (!this.isAvailable) { | |
delete this.backupStorage[key]; | |
return; | |
} | |
this.storage.removeItem(key); | |
} | |
} | |
export const local = new Storage('localStorage'); | |
export const session = new Storage('sessionStorage'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment