Page 8
More About Cookies
Because cookies involve writing to, and reading from,users' harddrives,security issues arise thatthe people who wrote Netscape,MSIE, andthe othercookie-friendly browsers had to confront. Ifyou're going tobe using cookies a lot, you should readMarc Slayton's That'stheWaythe Cookie Crumbles and CookiesRevisited. These articles will tell youwhat cookies are andteach youabout their built-in limitations. Themost important limitations for thistutorialare:
Not everyone has a cookie-friendly browser (but most do).
Noteveryone who has a cookie-friendly browser will acceptyour cookies (butmost will).
Each domain is allotted only 20cookies, so usethemsparingly.
Cookies must be no larger than 4 KB. That'sjust over 4,000characters, which isplenty.
With thoselimitations in mind, let's learn aboutsetting cookies.
SettingCookies
Setting a basiccookie is very easy. All you have todo is create a string in the formof cookie_name=value and thensetthe document.cookie propertyto that. The only trick:cookievalues must never have spaces,commas, or semicolons. Happily, youdon't really have to worry about thisbecause a pair of functions will code and decode your properties: they areescape()and unescape().
Our simple example,which stored yourname as a cookie, lookslikethis:
function setCookie(){ var the_name = prompt("What's your name?",""); var the_cookie = "wm_javascript=" + escape("username:" + the_name); document.cookie = the_cookie; alert("Thanks, now go to the next page.");}
The middle two lines ofthisfunction are the critical ones:
var the_cookie = "wm_javascript=" + escape("username:" + the_name);
If I entered "dave thau" at the prompt, this line wouldcreate a string that looks like wm_javascript=username%3Adave%20thau.This means that I'm going to save a cookie named wm_javascript to the hard drive.
That cookie is going to have the value username%3Adave%20thau the escape() function replaced the colon after username with %3A and the space between "dave" and "thau" with a %20.
When we read the cookie, we're going to look for the cookie named wm_javascript, then grab the username%3Adave%20thau, unescape() it, which changes the %3A back to a colon and the %20 back into a space, and then chop off the username:.