Created
October 28, 2018 11:08
-
-
Save dejanstojanovic/22b2fc26f3892affa986ad6d33963a5a to your computer and use it in GitHub Desktop.
HTML5 localStorage with expire
This file contains hidden or 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
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