存储在localStorage(作为HTML5中DOM存储的一部分)中的数据可用多长时间?我可以为本地存储的数据设置过期时间吗?
当前回答
来自W3C草案:
只有出于安全原因或用户请求时,用户代理才应该使本地存储区域的数据过期。用户代理应始终避免在可能访问该数据的脚本运行时删除数据。
你会想要使用setItem(键,值)对你的时间表进行更新;这将使用新数据添加或更新给定的键。
其他回答
您可以使用lscache。它会自动为您处理这个问题,包括存储大小超过限制的实例。如果发生这种情况,它将开始删除最接近指定到期日期的项。
自述:
lscache.set
Stores the value in localStorage. Expires after specified number of minutes.
Arguments
key (string)
value (Object|string)
time (number: optional)
这是常规存储方法之间唯一的真正区别。Get、remove等工作原理相同。
如果您不需要那么多的功能,您可以简单地存储一个带有值的时间戳(通过JSON),并检查它是否过期。
值得注意的是,将本地存储留给用户是有充分理由的。但是,当需要存储临时数据时,lscache之类的东西确实会派上用场。
如果您熟悉浏览器的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;
}
你可以试试这个。
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);
}
使用angular和local饲草的解决方案:
angular.module('app').service('cacheService', function() {
return {
set: function(key, value, expireTimeInSeconds) {
return localforage.setItem(key, {
data: value,
timestamp: new Date().getTime(),
expireTimeInMilliseconds: expireTimeInSeconds * 1000
})
},
get: function(key) {
return localforage.getItem(key).then(function(item) {
if(!item || new Date().getTime() > (item.timestamp + item.expireTimeInMilliseconds)) {
return null
} else {
return item.data
}
})
}
}
})
为了搜索者的利益:
像Fernando一样,当存储的值很简单时,我不想添加json加载。我只需要跟踪一些UI交互并保持数据的相关性(例如,用户在结账前是如何使用电子商务网站的)。
这将不符合每个人的标准,但希望是一个快速复制+粘贴启动器为某人和节省添加另一个库。
注意:如果您需要单独检索项目,这将不太好。
// Addition
if(window.localStorage){
localStorage.setItem('myapp-' + new Date().getTime(), 'my value');
}
// Removal of all expired items
if(window.localStorage){
// two mins - (1000 * 60 * 20) would be 20 mins
var expiryTime = new Date().getTime() - (1000 * 60 * 2);
var deleteRows = [];
for(var i=0; i < localStorage.length; i++){
var key = localStorage.key(i);
var partsArray = key.split('-');
// The last value will be a timestamp
var lastRow = partsArray[partsArray.length - 1];
if(lastRow && parseInt(lastRow) < expiryTime){
deleteRows.push(key);
}
}
// delete old data
for(var j=0; j < deleteRows.length; j++){
localStorage.removeItem(deleteRows[j]);
}
}
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?