存储在localStorage(作为HTML5中DOM存储的一部分)中的数据可用多长时间?我可以为本地存储的数据设置过期时间吗?


当前回答

生命周期由应用程序/用户控制。

从标准来看:

只有出于安全原因或用户请求时,用户代理才应该使本地存储区域的数据过期。用户代理应始终避免在可能访问该数据的脚本运行时删除数据。

其他回答

function setStorage(name,value){
    return localStorage.setItem(name,JSON.stringify({value:value,timestamp:Math.round((new Date()).getTime()/1000)}));
}
function getStorage(name,timeout){
    var object = JSON.parse(localStorage.getItem(name));
    if(object){
        if(Math.round((new Date()).getTime()/1000) < (object.timestamp+timeout)){
            return object.value;
        }else{
            localStorage.removeItem(name);
        }
    }
    return false;
}

生命周期由应用程序/用户控制。

从标准来看:

只有出于安全原因或用户请求时,用户代理才应该使本地存储区域的数据过期。用户代理应始终避免在可能访问该数据的脚本运行时删除数据。

不可能指定过期时间。这完全取决于用户。

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

当然,应用程序存储在客户机上的某些内容以后可能不再存在。用户可以显式地摆脱本地存储,或者浏览器可能会遇到空间问题。防御性的编程是很好的。然而,通常情况下,基于这个词的一些实际定义,事情仍然是“永远”的。

编辑——显然,如果你自己的应用程序认为它太旧了,它可以主动删除它。也就是说,您可以显式地在已保存的内容中包含某种时间戳,然后稍后使用该时间戳来决定是否应该刷新信息。

如果您熟悉浏览器的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;
}

您可以使用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之类的东西确实会派上用场。