Skip to content

Instantly share code, notes, and snippets.

@dominictobias
Last active March 21, 2019 11:21
Show Gist options
  • Save dominictobias/e078402b9d0264dd169f21dd246ec890 to your computer and use it in GitHub Desktop.
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
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