Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Forked from ksafranski/SimpleStore.js
Last active July 28, 2017 13:32
Show Gist options
  • Save stefanfrede/acbfa13ed236f7e71ac239e801947692 to your computer and use it in GitHub Desktop.
Save stefanfrede/acbfa13ed236f7e71ac239e801947692 to your computer and use it in GitHub Desktop.
Simple localStorage function with Cookie fallback for older browsers.
/**
* Simple [local|session]Storage with Cookie Fallback
* v.1.2.0
*
* USAGE:
* ----------------------------------------
* Set New / Modify:
* store({
* storage: {
* key: 'my_key',
* value: 'some_value',
* },
* });
*
* Retrieve:
* store({
* storage: {
* key: 'my_key',
* },
* });
*
* Delete / Remove:
* store({
* storage: {
* key: 'my_key',
* value: null,
* },
* });
*
*/
const store = function store({ storage, cookie = {} }) {
const key = storage.key;
const storageType = window[storage.type] || window['sessionStorage'];
const expirationDays = cookie.expirationDays || void 0;
let value = storage.value === null ? null : storage.value || void 0;
// Check for native support
const hasSupport = () => {
let isAvailable;
try {
const x = '__storage_test__';
storageType.setItem(x, x);
storageType.removeItem(x);
isAvailable = true;
}
catch(e) {
isAvailable = false;
}
return isAvailable;
}
// If value is detected, set new or modify store
if (value != null) {
// Convert object values to JSON
if (typeof value === 'object') {
value = JSON.stringify(value);
}
// Set the store
if (hasSupport) { // Native support
storageType.setItem(key, value);
} else { // Use Cookie
createCookie(key, value, expirationDays);
}
}
// No value supplied, return value
if (value === undefined) {
let data;
// Get value
if (hasSupport) { // Native support
data = storageType.getItem(key);
} else { // Use cookie
data = readCookie(key);
}
// Try to parse JSON...
try {
data = JSON.parse(data);
}
catch(e) {}
return data;
}
// Null specified, remove store
if (value === null) {
if (hasSupport) { // Native support
storageType.removeItem(key);
} else { // Use cookie
createCookie(key, '', -1);
}
}
/**
* Creates new cookie or removes cookie with negative expiration
* @param key The key or identifier for the store
* @param value Contents of the store
* @param exp Expiration - creation defaults to 30 days
*/
function createCookie(key, value, exp) {
const date = new Date();
date.setTime(date.getTime() + (exp * 24 * 60 * 60 * 1000));
const expires = exp != null ? `; expires=${date.toGMTString()}` : '';
document.cookie = `${key}=${value}${expires}; path=/`;
}
/**
* Returns contents of cookie
* @param key The key or identifier for the store
*/
function readCookie(key) {
const nameEQ = `${key}=`;
const ca = document.cookie.split(';');
for (let i = 0, max = ca.length; i < max; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment