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

前端 未结 4 1114
悲&欢浪女
悲&欢浪女 2021-02-07 14:31

I have a simple HTML5 App that I am currently working on and I\'m wondering if it\'s possible to remove a item in HTML5 Local Storage after a period of time, like: after 24 hour

4条回答
  •  抹茶落季
    2021-02-07 14:49

    You could store the date along with the data

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

提交回复
热议问题