Welcome to the OzoneAsylum FaqWiki
Frequently Asked Questions
DHTML/JavaScript

How do I set and read cookies in JavaScript? Pages that link to <a href="https://ozoneasylum.com/backlink?for=5536" title="Pages that link to How do I set and read cookies in JavaScript?" rel="nofollow" >How do I set and read cookies in JavaScript?\

Slime has provided a mini-tutorial on this:

quote:
Well, as you seem somewhat familiar with JavaScript, I'll give you a quick little tutorial...

document.cookie <- this is the object that contains and stores cookies.

Unlike most objects, you can't set it to a value and then read that value from it later. This is a weird object. When you set it to something, you're not really setting it to something. Instead, you're telling the browser to set a cookie. When you read from this object, you get a list of the cookies.


HOW TO SET A COOKIE

code:
document.cookie = "name=value; expires=date; path=whatever_path_you_want; 
domain=whatever_domain_you_want; secure";



OK, I don't understand half of that myself. The important parts? name=value - that's simple. The name of your cookie (might be "HasSeenSplashScreen") and the value that it's set to (might be "true", "false", "yabbadabbadoo", or anything you want).

expires=date specifies the date after which the browser is allowed to delete the cookie. You can use the Date object for that. I'll give an example later.

path=something ... well, i'm not exactly sure what this does, even though I could look it up. The safest thing to do is say "path=/";

The other things i don't even understand, and it's safe to leave them out, so I just ignore them.



EXAMPLE OF SETTING A COOKIE

code:
function setCookie(name, value, expires)
{
// no expiration date specified? use this date and it will just be deleted soon.
if (!expires) expires = new Date();
document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}
var expdate = new Date (); // pre-set to the current time and date
expdate.setTime(expdate.getTime() + 1000 * 60 * 60 * 24 * 365); // add one year to it
//365 days/year * 24 hours/day * 60 minutes/hour * 60 seconds/minute * 1000 milliseconds/second
// = howevermany milliseconds/year. So this adds one year, it'll expire in one year.
setCookie("skipSplash","true",expdate);




Note the use of the escape() function, which sort of encodes the cookie's value so that you don't have to worry about weird characters in it, which could mess stuff up. We unencode it later.


HOW TO READ PREVIOUSLY SET COOKIES

This is easier. When you read from document.cookie, you get a bunch of "name=value;" pairs. The expiration dates and all that junk aren't specified, you don't really need to know it anyway. The tricky part is when you have a lot of cookies, it can look like "myname=John;yourname=kars10;mypet=dog;yourpet=rodent;" it can get tough to pick out a specific cookie. Here's a function that will do it.


EXAMPLE OF READING A PREVIOUSLY SET COOKIE

code:
function getCookie(name)
{
var cookies = document.cookie;
if (cookies.indexOf(name) != -1)
{
var startpos = cookies.indexOf(name)+name.length+1;
var endpos = cookies.indexOf(";",startpos)-1;
if (endpos == -2) endpos = cookies.length;
return unescape(cookies.substring(startpos,endpos));
}
else
{
return false; // the cookie couldn't be found! it was never set before, or it expired.
}
}




That uses some fancy string manipulation to extract the value of the cookie and unencode it.

Just a couple things to keep in mind: the browser doesn't have to store more than 300 cookies total from anywhere on the internet, no more than 20 from your server, and no more than 4 kilobytes per cookie, counting both name and value.

You can't get a cookie set at another site, nor can another site get at your cookie.

Hope that helps, any questions, please ask - I may have been confusing. =)




from:
browser brain*?*



In 'sequel' to this Slime ran over similar ground and elaborated on certain points rounding of the explanation above:

quote:
Personally, I'm tired of all those pre-made functions that deal with cookies for you. Here's the very basics of it.

The document.cookie object contains all the cookies that have been set in the past. It returns name=value pairs separated by semicolons. If you've set a few cookies in the past, this property will contain something like "name=value;name=value;name=value". (Note that there's no semicolon after the last name=value pair.

OK, I'm sure you know enough about string manipulation to now read the value of a cookie you've set in the past. (Use String.indexOf(seacrhfor,startat) and String.substr(start,length) and String.substring(start,end). String.split(';') can also be very helpful.) Now here's how to set a cookie, and it's a little harder:

To set a cookie, you assign a value to document.cookie. This is a little weird, since when you assign the value, it doesn't actually *change* the document.cookie property! The browser just uses the information you're assigning to it to make a new cookie, but document.cookie will still return a name=value list as I said above. To set a cookie, use the following syntax:

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

The name and value are, obviously, the name and value that you want the cookie to have. The rest is a little harder. the expiration date must be written in a special form - this can be easily done by creating a Date object, setting it to when you want the cookie to expire, and then using the Date.toGMTString() function. If you want the cookie to expire immediately, don't include the expires=date in the string at all, or just set the date to the current time. Personally, I usually set the date to something like a year in advance.

The path is the path on your site where the cookie is allowed to be read. By default, the cookie can be read in any file in the same directory or a subdirectory of the one it was created in. I usually just set "path=/".

domain is what domains the cookie is allowed to be read on. I usually just omit this one, but you could use it if you had something like bugtown.ozones.com and you wanted the cookie to be allowed to be read there, you would set "domain=ozones.com".

The word "secure", if it's there, means that the cookie will use a secure connection to save it. I always omit this.

A few notes:

Always use the escape(string) and unescape(string) functions to encode the values of your cookies. Because if the cookie contains a character that's a semicolon, it can mess some stuff up. So before you set the value of the cookie, do something like value=escape(value); just to be safe, and after you read the value of the cookie, do value=unescape(value);.

Browsers are not required to remember more than 300 cookies total, and no more than 20 cookies per server. That means you're only allowed to set 20 cookies - that's not good if you use cookies on a bunch of your pages. On the other hand, browsers are required to allow 4 kilobytes per cookie (counting both name and value). So what you usually want to do is store lots of data in a single cookie. You might do this by making the value of the cookie "name=value;name2=value2;name3=value3;" and then saying value=encode(value);, and then writing the cookie under the name "ourWallsInfo".

That should do it.



from:
Best examples of 'cookie' coding


--------------------------------
Relevant threads:

Best examples of 'cookie' coding - a good discussion of the problem.

browser brain*?*

fun with cookies!

fun with cookies ][

DHTML, JavaScript and hiding DIV's

DHTML and cookies? - good recommendation of the cookie library.

safe code for cookies

My Cookies Have Crumbled - not much extra information but it is Wes' first post at the Asylum.

And a possible way of doing something similar without cookies:

A hint - Cookies without Cookies

Ini, Cookies but not cookies

Oh, and about those cookies without cookies..

--------------------------------
Relevant links:

Nibbler - a JavaScript library for cookie creation

Sample JavaScript for Tracking Site Visits via Cookies

JavaScript and cookies

The Unofficial Cookie FAQ

Session-only cookies

Making cookies with JavaScript


--------------------------------
Relevant FAQs:

How do I set and read cookies in PHP?

--------------------------------
Relevant notes:

As of the time of writing this FAQ was number 1 at Google for the terms javascript, set, cookies.

________________________
Emperor

(Added by: Emperor on Wed 29-Jan-2003)

(Edited by: kuckus on Sun 09-Mar-2003)

(Edited by: Emperor on Sat 10-May-2003)
(Edited by kuckus on 08-05-2004 18:55)
(Edited by kuckus on 08-05-2004 18:56)
(Edited by kuckus on 08-05-2004 18:57)

« BackwardsOnwards »

Show Forum Drop Down Menu