如何在特定本地存储变量上设置过期时间?
例如:如果我有一个页面免责声明,一旦用户点击了"accept“,我就会在本地存储中存储某个变量。然而,12小时后,我希望它被删除,并要求用户再次接受。
我不想将变量存储在会话存储中,因为每次用户打开新选项卡时,免责声明都会提示。
Cookie将是另一种解决方案,但如果可能的话,我宁愿不使用它。
谢谢!
发布于 2018-12-11 23:38:54
没有内置的方法可以使存储中的值过期。一种解决方案是存储时间戳,然后在每次访问时将存储的时间(如果有)与本地时间进行比较,以确定该值是否已过期。示例:
const expirationDuration = 1000 * 60 * 60 * 12; // 12 hours
const prevAccepted = localStorage.getItem("accepted");
const currentTime = new Date().getTime();
const notAccepted = prevAccepted == undefined;
const prevAcceptedExpired = prevAccepted != undefined && currentTime - prevAccepted > expirationDuration;
if (notAccepted || prevAcceptedExpired) {
alert("Disclaimer: ...");
localStorage.setItem("accepted", currentTime);
}发布于 2021-02-08 19:34:20
我强烈推荐使用lscache。只需将此2.5kb的JS包含到您的应用程序或每个CDN中。它具有高度的可配置性,并且使用起来非常简单。它支持字符串或对象。
If (lscache.get('myVar') === null) {
alert('time exceeded')
//set variable which will expire in 3 days
lscache.set('myVar', true, (60*24*3))
}https://stackoverflow.com/questions/53637930
复制相似问题