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


当前回答

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

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

其他回答

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

}

来自W3C草案:

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

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

你可以试试这个。

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

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

})

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

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

sessionStorage MDN: