Skip to content

Instantly share code, notes, and snippets.

@nydame
Last active October 20, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nydame/3c32c50c34de9a9e6a57fdfaa27552d0 to your computer and use it in GitHub Desktop.
Save nydame/3c32c50c34de9a9e6a57fdfaa27552d0 to your computer and use it in GitHub Desktop.
This JavaScript module lets you store information on the client with localStorage or sessionStorage with a fallback to cookies.
// import CookieMaster
// create an instance, e.g., ```cm = new CookieMaster("localStorage");```
// run ```cm.checkStoreKey(yourKey, yourValue);``` to store your information, providing that the key doesn't already exist
class CookieMaster {
constructor(type) {
// type = "sessionStorage" or "localStorage"; latter is default
this.type = type || "localStorage";
}
checkStoreKey(key, value) {
if (window.storageAvailable(this.type)) {
if (this.type === "sessionStorage" && sessionStorage.getItem(key) === null) {
sessionStorage.setItem(key, value);
return true;
}
return false;
} else if (this.type === "localStorage" && localStorage.getItem(key) === null) {
localStorage.setItem(key, value);
return true;
} else {
const allKeys = this.getCookieKeys();
if (allKeys.indexOf(key) === -1) {
this.setACookie(key, value);
return true;
}
return false;
}
}
setACookie(cookieKey, cookieValue) {
document.cookie = `${cookieKey}=${cookieValue}`;
}
getCookieKeys() {
return document.cookie.split(";").map(item => item.split("=")[0].trim());
}
storageAvailable(type) {
try {
var store = window.type;
} catch (e) {
} finally {
if (store === undefined) {
return false;
} else {
return true;
}
}
}
}
export default CookieMaster;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment