Skip to content

Instantly share code, notes, and snippets.

@anhang
Created July 20, 2011 23:07
Show Gist options
  • Star 95 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save anhang/1096149 to your computer and use it in GitHub Desktop.
Save anhang/1096149 to your computer and use it in GitHub Desktop.
HTML5 Local Storage with Expiration
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));
}
}
@claushellsing
Copy link

yep , i just find it :)

@kverawat
Copy link

Awesome, I found it too. Thank

@SpacemanPete
Copy link

Just found this gist too. Great share, thanks!

@awitherow
Copy link

Thanks for this @anhang!

@JimmyCrawford
Copy link

JimmyCrawford commented Mar 30, 2017

I can't believe that this is 6 years old and despite looking for how long local storage is valid for this is the (seemingly) only function that allows you to add an expiry date. Good Stuff @anhang!

@ashmohd
Copy link

ashmohd commented Aug 11, 2017

Thanks

@mindfulmike
Copy link

👍

@tomek-f
Copy link

tomek-f commented Nov 23, 2017

👍

@karladler
Copy link

karladler commented May 16, 2018

This would just not load the storage, while it is still available in the browser for other scripts.
Maybe a safer solution could be to encrypt the local storage and store the key in an cookie with expiry date?

@prakarangs
Copy link

7 years and still very helpful. Thank you!

@adc91
Copy link

adc91 commented Sep 3, 2018

Good contributions endure over time. Thank you.

@dysonspherelab
Copy link

@voku
Copy link

voku commented Nov 27, 2018

This code has one problem (as I see!?), it didn't delete the expired cache.

https://github.com/liesislukas/localstorage-ttl/blob/master/index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment