PDA

Click to See Complete Forum and Search --> : javascript cookies question


pnj
Sep 11th, 2002, 03:10 PM
I'm building an application that i need people to logon in order for them to view specific pages.

not a problem with that.

but what if they bookmark those pages?

how do i create a cookie in javascript that expires when they end the session or close the browser?

I doesn't need to be complex.

thanks for any tips or suggestions!

Rick Bull
Sep 12th, 2002, 04:44 AM
This is what I use, I think if you don't pass a date it expires at the end of the session:


//Sets a cookie. Send the name of the varible, the value, days until it expires - leave blank for no-expiration
function setCookie(cookieName, cookieValue, cookieExpiry) {
//If the date is not already in date format (i.e. days till expiry), and not missing
if (!(cookieExpiry instanceof Date) && cookieExpiry != null) {
//Convert the expiry date to the correct format
var expiryDate = new Date ();
expiryDate.setTime(expiryDate.getTime() + (cookieExpiry * 24 * 3600 * 1000));
cookieExpiry = expiryDate;
}
//Write the cookie, and the expiration date (if present)
document.cookie = cookieName + '=' + escape(cookieValue) + ((cookieExpiry == null) ? '' : '; expires=' + cookieExpiry.toGMTString());
return true;
}


If you want the rest of the JS file (reading/deleting cookies etc) just let me know.

pnj
Sep 12th, 2002, 10:16 AM
thanks!

yea, if you have the rest of the code that reads it that would be cool

what i'm going to do is, if the user trys to bookmark a page, i'll read the cookie. if it doesn't exist, send them back to the login page.

make sense?

thanks again!

Rick Bull
Sep 12th, 2002, 01:31 PM
Good idea. Here's the file, I think it all works fine. I added a function called sixMonths that returns the date plus six months, so that you can set cookies for that length of time.

pnj
Sep 12th, 2002, 01:49 PM
great!

thanks again!

Rick Bull
Sep 13th, 2002, 04:37 AM
You're welcome. :)