存储在localStorage(作为HTML5中DOM存储的一部分)中的数据可用多长时间?我可以为本地存储的数据设置过期时间吗?
当前回答
来自W3C草案:
只有出于安全原因或用户请求时,用户代理才应该使本地存储区域的数据过期。用户代理应始终避免在可能访问该数据的脚本运行时删除数据。
你会想要使用setItem(键,值)对你的时间表进行更新;这将使用新数据添加或更新给定的键。
其他回答
我建议将时间戳存储在localStorage中存储的对象中
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
您可以解析对象,获取时间戳并与当前Date进行比较,如果需要,还可以更新对象的值。
var object = JSON.parse(localStorage.getItem("key")),
dateString = object.timestamp,
now = new Date().getTime().toString();
compareTime(dateString, now); //to implement
或者,你也可以使用像localstorage-slim.js这样的轻量级包装器来处理这个问题。
如果您熟悉浏览器的locaStorage对象,就会知道没有提供过期时间的规定。但是,我们可以使用Javascript添加一个TTL(生存时间),使locaStorage中的项在一段时间后失效。
function setLocalStorageItem(key, value, ttl) {
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
let item = {
value: value,
expiry: ttl ? Date.now() + ttl : null
};
localStorage.setItem(key, JSON.stringify(item));
}
function getLocalStorageItem(key) {
let item = localStorage.getItem(key);
// if the item doesn't exist, return null
if (!item) return null;
item = JSON.parse(item);
// compare the expiry time of the item with the current time
if (item.expiry && Date.now() > item.expiry) {
// If the item is expired, delete the item from storage and return null
localStorage.removeItem(key);
return null;
}
return item.value;
}
如果有人还在寻找一个快速的解决方案,不想像jquery等依赖,我写了一个迷你库,添加过期到本地/会话/自定义存储,你可以在这里找到它的源代码:
https://github.com/RonenNess/ExpiredStorage
生命周期由应用程序/用户控制。
从标准来看:
只有出于安全原因或用户请求时,用户代理才应该使本地存储区域的数据过期。用户代理应始终避免在可能访问该数据的脚本运行时删除数据。
你可以试试这个。
var hours = 24; // Reset when storage is more than 24hours
var now = Date.now();
var setupTime = localStorage.getItem('setupTime');
if (setupTime == null) {
localStorage.setItem('setupTime', now)
} else if (now - setupTime > hours*60*60*1000) {
localStorage.clear()
localStorage.setItem('setupTime', now);
}
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- Twitter Bootstrap 3 Sticky Footer
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- CSS在特定的“内联块”项之前/之后换行
- 很好的初学者教程socket.io?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- 我如何删除背景图像在css?
- 如何克服HTML表单嵌套的限制?
- React: 'Redirect'没有从' React -router-dom'中导出