Create cookie on closing the browser window or tab - javascript

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()}`;
});

Related

Html and javascript cookie dying after browser window closes

I've added a darkmode setting to my website, and I made a cookie using javascript so it's saved for when you come back, everything works like a charm until you close the browser window.
var cookie = document.cookie = 'darkmode=false; SameSite=none; Secure';
Is there a way to make the cookie stay for as long as possible?
You should add expires and/or max-age for the cookie.
Check the documentation for more information.
var cookie = document.cookie = 'darkmode=false; max-age=31536000; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=none; Secure';

Is it safe to set cookie with unquoted path?

I would like to execute the following JavaScript to set a browser cookie:
document.cookie = "name=value;path='/'"
This works fine in Firefox, Chrome, and Safari. It does not work in IE, however. Removing the path part or unquoting '/' seems to set the cookie correctly in IE. I'm not an expert on the cookie spec. All of the guides online seem to quote the path. Is it required or optional to quote the path?
According to W3Schools correct syntax is following:
With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
http://www.w3schools.com/js/js_cookies.asp
Yes it is safe. it is the right way to do it when using plain old javascript.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
or via Jquery plugin jquery.cookie
$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });

Issue with Loading, Deleting and then Checking a JavaScript Cookie

On an enrollment page using forms on a Drupal module, I'm having trouble loading a cookie onto a series of pages. The purpose of the cookie is to have it load onto a multistep form, and then delete it when the form's done. On the next page, there is supposed to be a script that detects if the cookie still exists, but if it does it redirects the user back to the form.
The code I have for the form is here...
document.cookie = "visited=yes; path=/enrolled/";
$("#enroll-now-fifth-step #edit-return").click(function() {
document.cookie = "visited=yes; expires=Thu, 01 Jan 1970 00:00:01 GMT";
});
});
And the code for the page that detects the cookie and redirects the page back to the form if it exists is here...
document.cookie = "visited=yes; path=/enrolled/";
if (document.cookie.indexOf("visited") >= 0) {
location.href = "/enrolled/step-2";
} else {
document.cookie = "visited=yes; expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
I've been trying constantly for days with no luck. Any suggestions on what to do?

Understanding this go back logic

I saw this go back code in a website and I am trying to use it on my website. I am having trouble in understanding how the toURl and refUrl are being generated in it. Please guide about their structure. Thanks
var backtriggered = false;
setTimeout('goBack()',timer);
function goBack() {
if(backtriggered) return false;
backtriggered = true;
toURL=getWelcomeCookie('toURL');
refURL = getWelcomeCookie('refURL');
var reg = /(.*)\/sites\/(.*)\/(\d{4})\/(\d{2})\/(\d{2})\/(.*)\/?/;
if(reg.test(toURL) == false){
document.cookie="toURL"+ "=" +escape(toURL)+";path=/; domain=.mycsnippets.com; expires=Thu, 01-Jan-1900 00:00:01 GMT";
document.cookie="refURL"+ "=" +escape(toURL)+";path=/; domain=.mycsnippets.com; expires=Thu, 01-Jan-1900 00:00:01 GMT";
}
location.href=toURL;
}
document.cookie="toURL"+ "=" +escape(toURL)+";path=/; domain=.mycsnippets.com; expires=Thu, 01-Jan-1900 00:00:01 GMT";
This line puts a value in the brower's cookie store. For more information I think you should read this first: http://en.wikipedia.org/wiki/HTTP_cookie
There are two ways to set cookies: through server response, and through javascript.
What this code does is set cookies using javascript which say where the visitor has been and where he is going before setting the url to the target url (toURL). This way next page when it is called it knows to go back to the url which was set in the cookies as the previous url.

Javascript cookies and redirect

I need help changing this code so that the cookie only last through the session instead of 1 year forward. What changes do I need to make?
function createCookie(name,value,) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000*365));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
I tried to do this, but it doesn't seem to work. Cookie is created but doesn't disappear after session closes.
function createCookie(name,value) {
document.cookie = name+"="+value+"; path=/";
}
--- Update ---
I made some small changes to the code:
function createCookie(name,value,expires) {
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Now I was using Chrome, and it didn't work with the code I had and it doesn't work with this code either. But this code works in IE, Firefox and Opera. The cookie is deleted when the session is over, but not in Chrome...
Chrome since the version 19 had made a breakthrough change regarding the handling of session cookie. In order to improve the user experience the session cookie will not be removed.
If I understood correctly, since the option set in chrome settings say: "Continue where I left off", the session cookie never expires.
Please look at:
Chrome doesn't delete session cookies
If you are using Chrome or Firefox then set expires to 0, if you are using IE then leave out the expires parameter all together.

Categories