Javascript HTML5 本地存储中的项目何时过期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:49:05  来源:igfitidea点击:

When do items in HTML5 local storage expire?

javascripthtmllocal-storage

提问by user280427

For how long is data stored in localStorage (as part of DOM Storage in HTML5) available? Can I set an expiration time for the data which I put into localStorage?

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

采纳答案by Pointy

It's not possible to specify expiration. It's completely up to the user.

无法指定到期时间。这完全取决于用户。

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

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

Of course, it's possible that something your application stores on the client may not be there later. The user can explicitly get rid of local storage, or the browser may run into space considerations. It's good to program defensively. Generally however things remain "forever" based on some practical definition of that word.

当然,您的应用程序存储在客户端上的某些内容可能稍后不存在。用户可以明确地摆脱本地存储,否则浏览器可能会遇到空间问题。防御性编程很好。然而,一般情况下,根据该词的一些实际定义,事情仍然是“永远”的。

edit— obviously, your own application can actively remove stuff if it decides it's too old. That is, you can explicitly include some sort of timestamp in what you've got saved, and then use that later to decide whether or not information should be flushed.

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

回答by sebarmeli

I would suggest to store timestamp in the objectyou store in the localStorage

我建议将时间戳存储在您存储在 localStorage中的对象

var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));

You can parse the object, get the timestamp and compare with the current Date, and if necessary, update the value of the object.

您可以解析对象,获取时间戳并与当前日期进行比较,并在必要时更新对象的值。

var object = JSON.parse(localStorage.getItem("key")),
    dateString = object.timestamp,
    now = new Date().getTime().toString();

compareTime(dateString, now); //to implement

回答by huyz

You can use lscache. It handles this for you automatically, including instances where the storage size exceeds the limit. If that happens, it begins pruning items that are the closest to their specified expiration.

您可以使用lscache。它会自动为您处理,包括存储大小超过限制的实例。如果发生这种情况,它会开始修剪最接近其指定到期时间的项目。

From the readme:

来自readme

lscache.set

Stores the value in localStorage. Expires after specified number of minutes.

Arguments
key (string)
value (Object|string)
time (number: optional)

This is the only real difference between the regular storage methods. Get, remove, etc work the same.

这是常规存储方法之间唯一真正的区别。获取,删除等工作相同。

If you don't need that much functionality, you can simply store a time stamp with the value (via JSON) and check it for expiry.

如果您不需要那么多功能,您可以简单地存储一个带有值的时间戳(通过 JSON)并检查它是否过期。

Noteworthy, there's a good reason why local storage is left up to the user. But, things like lscache do come in handy when you need to store extremely temporary data.

值得注意的是,将本地存储留给用户是有充分理由的。但是,当您需要存储非常临时的数据时,lscache 之类的东西确实会派上用场。

回答by Fernando Fabreti

Brynner Ferreira, has brought a good point: storing a sibling key where expiration info resides. This way, if you have a large amount of keys, or if your values are large Json objects, you don't need to parse them to access the timestamp.

Brynner Ferreira 提出了一个很好的观点:在到期信息所在的位置存储同级密钥。这样,如果您有大量键,或者您的值是大型 Json 对象,则不需要解析它们来访问时间戳。

here follows an improved version:

下面是一个改进的版本:

 /*  removeStorage: removes a key from localStorage and its sibling expiracy key
    params:
        key <string>     : localStorage key to remove
    returns:
        <boolean> : telling if operation succeeded
 */
 function removeStorage(name) {
    try {
        localStorage.removeItem(name);
        localStorage.removeItem(name + '_expiresIn');
    } catch(e) {
        console.log('removeStorage: Error removing key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
        return false;
    }
    return true;
}
/*  getStorage: retrieves a key from localStorage previously set with setStorage().
    params:
        key <string> : localStorage key
    returns:
        <string> : value of localStorage key
        null : in case of expired key or failure
 */
function getStorage(key) {

    var now = Date.now();  //epoch time, lets deal only with integer
    // set expiration for storage
    var expiresIn = localStorage.getItem(key+'_expiresIn');
    if (expiresIn===undefined || expiresIn===null) { expiresIn = 0; }

    if (expiresIn < now) {// Expired
        removeStorage(key);
        return null;
    } else {
        try {
            var value = localStorage.getItem(key);
            return value;
        } catch(e) {
            console.log('getStorage: Error reading key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
            return null;
        }
    }
}
/*  setStorage: writes a key into localStorage setting a expire time
    params:
        key <string>     : localStorage key
        value <string>   : localStorage value
        expires <number> : number of seconds from now to expire the key
    returns:
        <boolean> : telling if operation succeeded
 */
function setStorage(key, value, expires) {

    if (expires===undefined || expires===null) {
        expires = (24*60*60);  // default: seconds for 1 day
    } else {
        expires = Math.abs(expires); //make sure it's positive
    }

    var now = Date.now();  //millisecs since epoch time, lets deal only with integer
    var schedule = now + expires*1000; 
    try {
        localStorage.setItem(key, value);
        localStorage.setItem(key + '_expiresIn', schedule);
    } catch(e) {
        console.log('setStorage: Error setting key ['+ key + '] in localStorage: ' + JSON.stringify(e) );
        return false;
    }
    return true;
}

回答by Dharmendrasinh Chudasama

Here highly recommended to use sessionStorage

这里强烈推荐使用sessionStorage

  • it is same as localStoragebut destroy when session destroyed / browser close
  • also localStoragecan share between tabs while sessionStoragecan use in current tab only, but value does not change on refresh page or change the page
  • sessionStorage is also useful to reduce network traffic against cookie
  • 它与localStorage相同,但在会话销毁/浏览器关闭时销毁
  • localStorage的可选项卡之间共享,而sessionStorage的只能在当前选项卡使用,但价值不会改变刷新页面或更改页面
  • sessionStorage 也可用于减少针对 cookie 的网络流量

for set value use

用于设定值

sessionStorage.setItem("key","my value");

for get value use

获取价值使用

var value = sessionStorage.getItem("key");

click here for view api

点击这里查看api

all ways for set are

设置的所有方法都是

  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");

all ways for get are

所有获取方式都是

  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");

回答by Robert Peake

While local storage does not supply an expiration mechanism, cookies do. Simply pairing a local storage key with a cookie provides an easy way to ensure that local storage can be updated with the same expiration parameters as a cookie.

虽然本地存储不提供过期机制,但 cookie 可以。简单地将本地存储密钥与 cookie 配对提供了一种简单的方法来确保可以使用与 cookie 相同的过期参数来更新本地存储。

Example in jQuery:

jQuery 中的示例:

if (!$.cookie('your_key') || !localStorage.getItem('your_key')) {
    //get your_data from server, then...
    localStorage.setItem('your_key', 'your_data' );
    $.cookie('your_key', 1);
} else {
    var your_data = localStorage.getItem('your_key');
}
// do stuff with your_data

This example sets a cookie with the default parameter to expire when the browser is closed. Thus, when the browser is closed and re-opened, the local data store for your_data gets refreshed by a server-side call.

本示例将带有默认参数的 cookie 设置为在浏览器关闭时过期。因此,当浏览器关闭并重新打开时,your_data 的本地数据存储会通过服务器端调用刷新。

Note that this is not exactly the same as removingthe local data store, it is instead updating the local data store whenever the cookie expires. However, if your main goal is to be able to store more than 4K client-side (the limitation for cookie size), this pairing of cookie and local storage will help you to accomplish a larger storage size using the same expiration parameters as a cookie.

请注意,这与删除本地数据存储并不完全相同,而是在 cookie 过期时更新本地数据存储。但是,如果您的主要目标是能够存储超过 4K 的客户端(cookie 大小的限制),这种 cookie 和本地存储的配对将帮助您使用与 cookie 相同的到期参数来实现更大的存储大小.

回答by jldupont

The lifecycle is controlled by the application/user.

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

From the standard:

标准

User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user. User agents should always avoid deleting data while a script that could access that data is running.

用户代理应该仅出于安全原因或当用户要求这样做时才使本地存储区域中的数据过期。用户代理应始终避免在可以访问数据的脚本运行时删除数据。

回答by FatherStorm

From the W3C draft:

来自 W3C 草案:

User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user. User agents should always avoid deleting data while a script that could access that data is running.

用户代理应该仅出于安全原因或当用户要求这样做时才使本地存储区域中的数据过期。用户代理应始终避免在可以访问数据的脚本运行时删除数据。

You'll want to do your updates on your schedule using setItem(key, value); that will either add or update the given key with the new data.

您需要使用 setItem(key, value) 来按计划进行更新;这将使用新数据添加或更新给定的键。

回答by Brynner Ferreira

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

}

回答by Ronen Ness

If anyone still looking for a quick solution and don't want dependencies like jquery etc I wrote a mini lib that add expiration to local / session / custom storage, you can find it with source here:

如果有人仍在寻找快速解决方案并且不想要像 jquery 等依赖项,我编写了一个迷你库,将过期添加到本地/会话/自定义存储,您可以在此处找到它的源代码:

https://github.com/RonenNess/ExpiredStorage

https://github.com/RonenNess/ExpiredStorage