Reading Cookies

Once you have a cookie on someone's hard disk, it's easy to read.

Whenever your browser opens a Web page, it calls in whatever cookies it can, then loads them into the document.cookie property.

Reading cookies is getting the information you want out of them.

The cookie we set looks like this: mycookie=username:fred%20derf

When we want to read the cookie, we will

Here is a javascript function that reads mycookie:

function readCookie(){
var the_cookie = document.cookie;
var broken_cookie = the_cookie.split(":"); //creates an array, broken_cookie[]
var your_name = broken_cookie[1];
var your_name = unescape(your_name);
alert("Your name is: " + your_name);
}

After the first line everything is devoted to getting the username out of the cookie.

Here's a breakdown of that process:

var broken_cookie = the_cookie.split(":"); Splits the cookie into two parts at the colon.
var the_name = broken_cookie[1]; Grab the part after the colon, which is fred%20derf.
var the_name = unescape(the_name); Undo the stuff that the escape() function created. In this case, it pulled out the space and dropped in %20. Swap the space back in with unescape().
alert("Your name is: " + the_name); Display the result

Our example was a very simple one.


Exercise
Build two web pages, one containing the bake cookie javascript function the other containing the read cookie javascript function.