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


当前回答

如果有人使用jQuery的jStorage插件,它可以添加过期的setTTL功能,如果jStorage插件

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

其他回答

这里强烈推荐使用sessionStorage

它与localStorage相同,但在会话销毁/浏览器关闭时销毁 此外,localStorage可以在选项卡之间共享,而sessionStorage只能在当前选项卡中使用,但值不会在刷新页面或更改页面时改变 sessionStorage对于减少cookie的网络流量也很有用

用于设置值使用

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

获取值使用

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

点击这里查看API

集合的所有方式都是

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

所有得到的方法都是

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

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

来自W3C草案:

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

你会想要使用setItem(键,值)对你的时间表进行更新;这将使用新数据添加或更新给定的键。

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

从标准来看:

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

Javascript localStorage没有任何设置过期时间的选项

然后我使用这些函数来检查支持,设置和获取

function ls_support(){
    return "localStorage" in window&&window["localStorage"]!==null;
}

function lsset(key,val,exp){
    if(ls_support()){
        if(!exp) exp=600;// = 10 minutes Default
        localStorage[key]=
            JSON.stringify({
                "val":val,
                "exp":~~((new Date()).getTime()/1000)+exp
            });
    }
}

function lsget(key){
    if(ls_support()){
        str=localStorage[key];
        if("undefined"!=typeof(str)&&str.length){
            try{// is json or not
                json=JSON.parse(str);
            }catch(e){// if variable not set via lsset func
                //json.exp=false;// will return null
                return str;// will return original variable
            }
            if(json.exp){// variable setted via lsset func
                if(~~((new Date()).getTime()/1000)>json.exp){// expired
                    delete localStorage[key];
                }else{
                    return json.val;
                }
            }
        }
    }
    return null;
}

这似乎很有效: