一段时间后删除HTML5本地存储中的项目

Removing an item in HTML5 Local Storage after a period of time?

本文关键字:存储 项目 删除 HTML5 一段时间      更新时间:2023-09-26

我有一个简单的HTML5应用程序,我目前正在开发中,我想知道是否有可能在一段时间后删除HTML5本地存储中的项目,例如:24小时后,删除此项目等。

我想JavaScript中内置的Date Object可能正是我所需要的。

这可能吗?如果可以的话,一些代码示例会很好,谢谢!

您可以将日期与数据一起存储

//add data we are interested in tracking to an array
var values = new Array();
var oneday = new Date();
oneday.setHours(oneday.getHours() + 24); //one day from now
values.push("hello world");
values.push(oneday);
try {
    localStorage.setItem(0, values.join(";"));
} 
catch (e) { }
//check if past expiration date
var values = localStorage.getItem(0).split(";");
if (values[1] < new Date()) {
    localStorage.removeItem(0);
}

使用此解决方案:

(function () {
  var lastclear = localStorage.getItem('lastclear'),
      time_now  = (new Date()).getTime();
  // .getTime() returns milliseconds so 1000 * 60 * 60 * 24 = 24 days
  if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
    localStorage.clear();
    localStorage.setItem('lastclear', time_now);
  }
})();

如果你想做到这一点,我认为你基本上必须手动完成。例如,您可以将时间戳与存储的每个值一起存储在localStorage插槽中,然后按照页面加载或setTimeout之类的规则间隔,对照当前时间检查时间戳。

示例:

//this function sets the value, and marks the timestamp
function setNewVal(prop)
{
    window.localStorage[prop] = Math.random();
    window.localStorage[prop+"timestamp"] = new Date();
}
//this function checks to see which ones need refreshing
function someRucurringFunction()
{
    //check each property in localStorage
    for (var prop in window.localStorage)
    {   //if the property name contains the string "timestamp"
        if (prop.indexOf("timestamp") != -1)
        {   //get date objects
            var timestamp = new Date(window.localStorage[prop]);
            var currentTime = new Date();
            //currently set to 30 days, 12 hours, 1 min, 1s (don't set to 0!)
            var maxAge =    (1000   *   1)  *//s
                            (60     *   1)  *//m
                            (60     *  12)  *//h
                            (24     *  30);  //d
            if ((currentTime - timestamp) > maxAge)
            {//if the property is too old (yes, this really does work!)
                //get the string of the real property (this prop - "timestamp")
                var propString = prop.replace("timestamp","");
                //send it to some function that sets a new value
                setNewVal(propString);
            }
        }
    }
}
//set the loop
window.setInterval(someRucurringFunction,(1000*60*60);

编辑:mrtsherman的方法也完全可行。同样,您可以使用JSON.stringfy/parse()输入时间戳作为存储/检索对象的属性。如果数组或对象非常大,或者您有很多,为了提高效率,我可能建议使用并行属性方法。

window.setInterval(function () {
        localStorage.setItem('nicwincount', 0);
},8640000); //24 * 60mins * 60sec

ps:nicwincount是您之前设置的本地存储。localStorage.setItem("feeds",Ext.encode(feeds));

希望能帮助你。