HTML5本地存储中的项何时到期?

use*_*427 316 javascript html5 local-storage

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

seb*_*eli 255

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

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

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

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

compareTime(dateString, now); //to implement
Run Code Online (Sandbox Code Playgroud)

  • 好吧,即使客户端时间不一致,您仍然可以找到一种使用服务器时间的方法.就像将时间戳回显到div一样. (3认同)

Poi*_*nty 201

无法指定过期时间.这完全取决于用户.

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

当然,您的应用程序存储在客户端上的某些内容可能不会在以后出现.用户可以明确地摆脱本地存储,或者浏览器可能会遇到空间考虑.防守计划很好.一般情况下,根据该词的某些实际定义,事物仍然"永远".

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

  • @AndresRiofrio我找不到Mozilla或Microsoft或W3C中任何规定任何强制到期的文档.因此,我认为答案是肯定的,用户代理应该永远保存存储的东西,或者直到用户明确要求删除它(或者我想直到你自己的应用程序删除它自己的东西). (6认同)
  • 这也意味着您的浏览器不断增长.你使用一次应用程序,它会将它存储在你的浏览器中,它永远存在于那里...... (3认同)
  • 那么用户可以指望在一年后才能获得数据吗?除非用户“明确”删除数据,否则开发人员能否指望数据可用? (2认同)
  • Firefox 有一个记录在案的[驱逐政策](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria)。 (2认同)

huy*_*uyz 34

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

来自readme:

lscache.set

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

Arguments
key (string)
value (Object|string)
time (number: optional)
Run Code Online (Sandbox Code Playgroud)

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

如果您不需要那么多功能,您只需存储带有值(通过JSON)的时间戳并检查它是否到期.

值得注意的是,本地存储留给用户的理由很充分.但是,当你需要存储非常临时的数据时,像lscache这样的东西会派上用场.


Fer*_*eti 32

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

以下是改进版本:

 /*  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;
}
Run Code Online (Sandbox Code Playgroud)


小智 24

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

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
Run Code Online (Sandbox Code Playgroud)

此示例设置一个cookie,其默认参数在浏览器关闭时到期.因此,当浏览器关闭并重新打开时,your_data的本地数据存储将通过服务器端调用进行刷新.

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

  • 请记住,每次请求都会发送Cookie. (9认同)

Dha*_*ama 22

强烈建议使用sessionStorage

  • 它与localStorage相同,但在会话销毁/浏览器关闭时销毁
  • sessionStorage对于减少针对cookie的网络流量也很有用

用于设定值的使用

sessionStorage.setItem("key","my value");
Run Code Online (Sandbox Code Playgroud)

获得价值

var value = sessionStorage.getItem("key");
Run Code Online (Sandbox Code Playgroud)

点击这里查看api

所有的方式都是

  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");
Run Code Online (Sandbox Code Playgroud)

所有得到的方式都是

  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“ sessionStorage”不适用于在标签之间共享数据 (5认同)

jld*_*ont 13

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

标准:

用户代理应仅出于安全原因或用户请求时从本地存储区域过期数据.在可以访问该数据的脚本正在运行时,用户代理应始终避免删除数据.


Fat*_*orm 9

从W3C草案:

用户代理应仅出于安全原因或用户请求时从本地存储区域过期数据.在可以访问该数据的脚本正在运行时,用户代理应始终避免删除数据.

您将希望使用setItem(键,值)按计划进行更新; 这将使用新数据添加或更新给定的密钥.


Bry*_*ira 9

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

}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这种方法,因为它不需要先解析数据. (4认同)

小智 7

你可以试试这个。

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您熟悉浏览器的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;
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mit 5

如果有人使用 jQuery 的 jStorage 插件,则可以使用 setTTL 函数添加过期时间(如果 jStorage 插件)

$.jStorage.set('myLocalVar', "some value");
$.jStorage.setTTL("myLocalVar", 24*60*60*1000); // 24 Hr.
Run Code Online (Sandbox Code Playgroud)


Ron*_*ess 5

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

https://github.com/RonenNess/ExpiredStorage