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


当前回答

使用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
        }
      })
    }
  }

})

其他回答

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

你可以试试这个。

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

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

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

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

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

https://github.com/RonenNess/ExpiredStorage