Skip to content
Advertisement

I’m trying to change the localstorage expiration time from forever to 24 hours

I have implemented a dialogue which shows whenever a user access the website. However, I want the dialogue to reappear after 24 hours if someone accesses the site clicking on the cookie. Unfortunately, I spent a lot of time researching and I haven’t found any solution which applies to my scenario. Below is the code I’m trying to modify,

var is_dialogue = window.localStorage.getItem("dialogue");
if (is_dialogue != 'false') {
    var today = new Date();
    var hours = today.getHours();
    dialogue = new Dialogue();
    dialogue.setHtmlMessage(string('dialogue-heading'));
    dialogue.addHtmlDetail(string('dialogue-detail'));

    if (((today.getHours() + 24) >= 24) || ((today.getHours() + 24) <= 48))
       localStorage.setItem("dialogue", "true");
}

Advertisement

Answer

localStorage has no expiration time, but you can compare timestamps:

function moreThanOneDayAgo(date) {
    const DAY = 1000 * 60 * 60 * 24;
    const dayAgo = Date.now() - DAY;

    return date < dayAgo;
}

var is_dialogue = localStorage.getItem("dialogue");
if (is_dialogue === null || moreThanOneDayAgo(is_dialogue)) {
    dialogue = new Dialogue();
    dialogue.setHtmlMessage(string('dialogue-heading'));
    dialogue.addHtmlDetail(string('dialogue-detail'));

    localStorage.setItem("dialogue", Date.now());
}
Advertisement