I have a problem. I want to create a cookie in JavaScript and I do it like the following:
document.cookie = "type=banner;expires=Thu, 25 Nov 2020 08:50:17 GMT";
Now the problem is that when I close the browser I want this cookie to expire and also to create a new one just like this document.cookie = "type=popup;expires=Thu, 25 Nov 2020 08:50:17 GMT";
How can I achieve the following functionality in JavaScript?
First of all you can listen for the beforeunload event. This happens "when the window, the document and its resources are about to be unloaded." BeforeUnloadEvent - Web APIs. A cookie can be deleted by setting its expires to zero Document.cookie - Web APIs. And then you can add the new one.
window.addEventListener('beforeunload', e => {
//"delete" the old cookie
document.cookie = "type=banner;expires=0";
//add the new cookie
var expires = new Date();
expires.setHours(expires.getHours()+2); // expires in two hours
document.cookie = `type=popup;expires=${expires.toUTCString()}`;
});