Reputation: 141
I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false
any idea why?
Upvotes: 0
Views: 742
Reputation: 141
I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};
Upvotes: 1
Reputation: 1782
I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies
code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem()
or docCookies.removeItem()
work incredible well.
Upvotes: 0
Reputation: 53705
document.cookie = ...
sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)
Upvotes: 0