Last active
January 7, 2020 06:15
-
-
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.
This file contains 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
// 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