PDA

View Full Version : Set Cookie Expiry Date for current session


RealBeginner
07-17-2002, 12:18 PM
Hi All,

I have the following setCookie function that I use to set a cookie. The problem is that I want to set the cookie that it is only valid for the time that a user is on my site. As soon as he leaves the cookie value must be set to "no".

Any help would be appreciated.

function SetCookie(name, value, expires, days, path)
{
var cookies = document.cookie; // cookies for site
var ix1; // index
var n1 = name; // main cookie name
var n2 = ""; // crumb name
var out; // returned value
var p2 = value; // new value
var p3 = expires; // param work area
var p4 = days;
var msd = 1000 * 60 * 60 * 24; // milisecs per day
if (!p3) { // no expiration
if (!p4) { p4 = 1; } // no days: use 1
p3 = new Date();
p3.setTime(p3.getTime() + msd * days);
}
ix1 = n1.indexOf(";"); // cookie/crumb break
if (ix1 != -1) {
n2 = n1.substring(ix1 + 1); // crumb name
n1 = n1.substring(0, ix1); // main cookie name
}
out = GetCookieCrumb(cookies, n1);
if (n2) {
if (out) { out = GetCookieCrumb(out, n2); }
else { rest = ""; }
if (rest) { p2 = rest + ";" + n2 + "=" + p2; }
else { p2 = n2 + "=" + p2; }
}
document.cookie=n1+"="+escape(p2)+"; expires="+p3.toGMTString()+ ";path=/;"
}


onClick="set();"

function set()
{
SetCookie("loggedin", 'yes', "",xx);
}

nolachrymose
07-17-2002, 02:21 PM
To set a cookie for the current session, just use this line of code:

document.cookie="loggedin=yes;path=/";

Hope that helps!

Happy coding! :)

tamienne
07-17-2002, 02:56 PM
I'm a little confused...Why would you need to set it to 'no'? No other site should be able to read the cookie anyway and if the person is off your site then you can't read it either.

Now, if you just want to go with a session Cookie that's the easiest--just remove the expires piece for the cookie. This will make the cookie valid until the browser shuts down.

If you really want something for just your site, you can add a function to all your pages during onLoad and onUnload to set the appropriate message.