Reputation: 21118
I'm trying to set cookie that would last after browser is closed. Though every-time I close browser, cookie disappears. I thought cookies supposed to be kept even if browser is closed? Unless specified to be deleted after some time?
For example:
console.log("cookies ", document.cookie)
document.cookie = "some_cookie=true; max-age=31536000";
First time opening page with this JS code, it prints cookies
.
After refreshing browser, it prints cookies some_cookie=true
After closing browser and opening same page again, it prints cookies
.
I tested on Firefox 65.0.2 (64-bit), Chrome 72.0.3626.109 (Official Build) (64-bit) and Chromium 71.0.3578.98 (Official Build) Built on Ubuntu , running on Ubuntu 16.04 (64-bit)
(for Chrome and Chromium had to use http server, because it would not allow to set cookies at all, if raw html file was opened directly).
Results are all the same, after I close browser, my cookie is deleted. I also checked if there was an option to clear cookies on closing browser, but it is not enabled.
Am I doing something wrong here? Or cookies are outdated and I should just stick to localStorage
?
P.S. I tried using max-age
, expires
or not using those at all, but result is the same.
Upvotes: 3
Views: 5139
Reputation: 21118
For me what worked, was to specify max-age
when storing cookie. But also when testing I had to use web server to serve my html file, because opening plain html file directly on browser, does not make it to be stored up to specified duration. Even if it says it will expire on some date, it still deletes cookie when browser is closed (this is kind of inconsistent).
So default behavior is it expires when session is closed, and to change that, need to specify some duration via expires
or max-age
attributes.
As per Mozzila documentation: "If neither expires nor max-age specified it will expire at the end of session."
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#Write_a_new_cookie
Upvotes: 3