Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active January 7, 2020 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RadGH/8915e3c7d058c02d796b95a640b53429 to your computer and use it in GitHub Desktop.
Save RadGH/8915e3c7d058c02d796b95a640b53429 to your computer and use it in GitHub Desktop.
JavaScript storage using localstorage with Get, Set, Delete. Falls back to 30-day cookies if LocalStorage is not supported.
// Usage:
cache.set('name', 'Radley');
alert( cache.get('name') ); // Displays "Radley"
cache.delete('name');
alert( cache.get('name') ); // Displays ""
// End of usage. Note that this code must go below the actual cache definition (below)
// --------------
// Caching mechanism
let cache = new function() {
let date_now = new Date();
let date_30days = new Date();
date_30days.setTime( date_now.getTime() + (1000*60*60*24*30) ); // ms, s, m, h, d
this.set = function( name, value ) {
try {
localStorage.setItem( name, value );
} catch(e) {
document.cookie = name + "=" + value + ";path=/;expires=" + date_30days.toGMTString();
}
};
this.get = function( name ) {
try {
return localStorage.getItem( name );
} catch(e) {
let v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
};
this.delete = function( name ) {
try {
localStorage.removeItem( name );
} catch(e) {
document.cookie = name + "=;path=/;expires=" + date_now.toGMTString();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment