Not sure why expiration isn’t built into the HTML5 specs for LocalStorage, but I put together this little snippet today.
It uses Modernizr (http://www.modernizr.com/) to check for LocalStorage support.
AZHU.storage = { save : function(key, jsonData, expirationMin){ if (!Modernizr.localstorage){return false;} var expirationMS = expirationMin * 60 * 1000; var record = {value: JSON.stringify(jsonData), timestamp: new Date().getTime() + expirationMS} localStorage.setItem(key, JSON.stringify(record)); return jsonData; }, load : function(key){ if (!Modernizr.localstorage){return false;} var record = JSON.parse(localStorage.getItem(key)); if (!record){return false;} return (new Date().getTime() < record.timestamp && JSON.parse(record.value)); } }
Gist: https://gist.github.com/1096149
Post a Comment