Once you save a cookie to someone's hard disk, it's easy toread.Here'sthe code that reads the examplecookie:function readCookie(){ var the_cookie = document.cookie; var the_cookie = unescape(the_cookie); var broken_cookie = the_cookie.split(":"); var the_name = broken_cookie[1]; alert("Your name is: " + the_name);}
The firstline is theimportant one. Whenever your browser opens aWeb page, itcalls inwhatever cookies it can, then loads them into thedocument.cookieproperty.
The tricky part about reading cookies is getting the information you want out of them. Remember, the cookie we set looks like this: wm_javascript=username%3Adave%20thau. Everything after the first line of the function is devoted to pulling the username out of the cookie. Here's a breakdown of that process:
- var the_cookie = unescape(the_cookie);
- Undo the stuff that the escape() function created. In this case, unescape() swaps the %3A with a colon, and the %20 with a space.
- var broken_cookie = the_cookie.split(":");
- Split the cookie into two parts at the colon.
- var the_name = broken_cookie[1];
- Grab the part after the colon, which is dave thau.
- alert("Your name is: " + the_name);
- Yee-haw!
This example used acookie that only stored onebit of information: theusername. As Isaid before, cookies can storeup to 4 KB, which leaves plenty of room forquite a bit more information.
next page»