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


当前回答

@sebarmeli的方法在我看来是最好的,但是如果你只想在一个会话的生命周期内保存数据,那么sessionStorage可能是一个更好的选择:

这是一个维护存储区域的全局对象(sessionStorage) 在页面会话期间可用。页面会话 只要浏览器打开,就会持续,并在页面上存活 重新加载和恢复。在新选项卡或窗口中打开一个页面会导致 要启动的新会话。

sessionStorage MDN:

其他回答

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

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

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

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

使用angular和local饲草的解决方案:

angular.module('app').service('cacheService', function() {

  return {
    set: function(key, value, expireTimeInSeconds) {
      return localforage.setItem(key, {
        data: value,
        timestamp: new Date().getTime(),
        expireTimeInMilliseconds: expireTimeInSeconds * 1000
      })
    },
    get: function(key) {
      return localforage.getItem(key).then(function(item) {
        if(!item || new Date().getTime() > (item.timestamp + item.expireTimeInMilliseconds)) {
          return null
        } else {
          return item.data
        }
      })
    }
  }

})

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

https://github.com/RonenNess/ExpiredStorage

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

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

这似乎很有效: