dumbledad
dumbledad

Reputation: 17527

Having session cookies expire when the browser closes but still sent to server

I'm confused about cookies. If I write a cookie like this

 document.cookie = "userName=" + me.name + ";";

then it is passed to the server with Ajax calls and page loads (where I read and use the value). However the cookie also persists between visits, i.e. it is still there if the browser is closed and re-opened. I don't want that. But if I set it as a session cookie like this

 document.cookie = "userName=" + me.name + "; expires=;";

then it is correctly deleted when the browser closes, but it is not sent to the server with Ajax calls and page loads.

(N.B. the persisting between browser sessions may be an IE10 beta bug, other posts suggest that my first line should produce a cookie that expires when the browser closes.)

What's the difference between these two lines in terms of the kind of cookie created, and if I want a cookie that dies when the browser closes, but is passed to the server, then what is the correct JavaScript to set it?

Upvotes: 1

Views: 7979

Answers (1)

user753137
user753137

Reputation:

If you do not specify a expiration time for your cookie, it normally expires when the session ends/browser is closed.

I am not sure what kind of side effect + " (opening double quote) would cause at the end of following code. No syntax error?

document.cookie = "userName=" + me.name + ";

You meant?

document.cookie = "userName=" + me.name;

Also, is there a chance that you already have a persistent cookie set in which case only the second code will change it to a session cookie?

Upvotes: 2

Related Questions