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");
}
CodePudding user response:
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());
}
CodePudding user response:
I would use date-fns/differenceInHours or a similar library, but it's up to you:)
In a global script:
const checkTimestamp = (timestamp) => {
return differenceInHours(new Date(), timestamp) > 24;
}
const isUserConsentExpired = () => {
const timestamp = localStorage.getItem(***);
return timestamp
? checkTimestamp(timestamp)
: false
}
window.onload(() => {
if(!isUserConsentExpired) {
return;
}
... open cookie dialog...
})
CodePudding user response:
I suggest you to use the cookie, against localStorage, because there the expiration is solved, you don't have to code for this feature. Here is an example below!
And I found a post about the differences between localSotrage and cookie, if you would like to know more about this topic.
Cookies vs. LocalStorage: What’s the difference?
function setCookie(cookieName, cookieValue, exDays) {
const date = new Date();
date.setTime(date.getTime() exDays * 24 * 60 * 60 * 1000);
let expires = "expires=" date.toUTCString();
document.cookie = `${cookieName}=${cookieValue};${expires};path=/`;
}
setCookie("cookieName", "cookieValue", 30)