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


当前回答

你可以试试这个。

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);
}

其他回答

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

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

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

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

你可以试试这个。

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);
}

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

// Functions
function removeHtmlStorage(name) {
    localStorage.removeItem(name);
    localStorage.removeItem(name+'_time');
}

function setHtmlStorage(name, value, expires) {

    if (expires==undefined || expires=='null') { var expires = 3600; } // default: 1h

    var date = new Date();
    var schedule = Math.round((date.setSeconds(date.getSeconds()+expires))/1000);

    localStorage.setItem(name, value);
    localStorage.setItem(name+'_time', schedule);
}

function statusHtmlStorage(name) {

    var date = new Date();
    var current = Math.round(+date/1000);

    // Get Schedule
    var stored_time = localStorage.getItem(name+'_time');
    if (stored_time==undefined || stored_time=='null') { var stored_time = 0; }

    // Expired
    if (stored_time < current) {

        // Remove
        removeHtmlStorage(name);

        return 0;

    } else {

        return 1;
    }
}

// Status
var cache_status = statusHtmlStorage('cache_name');

// Has Data
if (cache_status == 1) {

    // Get Cache
    var data = localStorage.getItem('cache_name');
    alert(data);

// Expired or Empty Cache
} else {

    // Get Data
    var data = 'Pay in cash :)';
    alert(data);

    // Set Cache (30 seconds)
    if (cache) { setHtmlStorage('cache_name', data, 30); }

}

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

从标准来看:

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