Skip to content

Instantly share code, notes, and snippets.

@dejanstojanovic
Created October 28, 2018 11:08
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 dejanstojanovic/22b2fc26f3892affa986ad6d33963a5a to your computer and use it in GitHub Desktop.
Save dejanstojanovic/22b2fc26f3892affa986ad6d33963a5a to your computer and use it in GitHub Desktop.
HTML5 localStorage with expire
var localStorageEx = {
get: function (key) {
var value = localStorage[key];
if (value != null) {
var model = JSON.parse(value);
if (model.payload != null && model.expiry != null) {
var now = new Date();
if (now > Date.parse(model.expiry)) {
localStorage.removeItem(key);
return null;
}
}
return JSON.parse(value).payload;
}
return null;
},
set: function (key, value, expirySeconds) {
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + expirySeconds);
localStorage[key] = JSON.stringify({
payload: value,
expiry: expiryDate
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment