November 8, 2006
Want a Cookie?
Cookies are really the only way in which you can share user data between two non-sequential web pages. Cookies allow you to store data on users’ systems and retrieve it in minutes, hours or even days later. This makes cookies perfect for remembering things like users' login names, which pages they visited last, what they dropped into their shopping carts and when they did so.
Although server-side code is the most robust method of dealing with cookies, sometimes you need to manipulate cookies on the client side. Luckily, JavaScript can read and write cookies in exactly the same way servers do. Though the problem with JavaScript is that reading a cookie requires a little parsing to get them out. Don't worry, I found a nice little function to the job for us.
Any script be it server or client-side can only read cookies that were set by a web page from the same domain. Cookies are stored in the document object’s cookie property. This property is actually a string that’s automatically generated by the browser when the page loads. It concatenates all the valid cookie information stored for the current browser address, and makes it available to JavaScript via the DOM.
Within the cookie property, cookies are separated by a semicolon (;), and traditionally each cookie consists of a name/value pair separated by an equality sign (=).
Writing a Cookie
An example cookie string looks like this:
fur=blue; food=biscuits; name=Cookie_Monste
The first step in creating a cookie is to create a string that reflects the name of your cookie, followed by =, followed by the value of the cookie:
var cookieName = "login"; var cookieValue = "choc_chip"; var theCookie = cookieName + "=" + cookieValue;
note: When you create your cookie string, make sure that the name or value of the cookie does not include spaces, commas, or semicolons. These characters can cause errors not only with the parsing of the cookie string, but with the sending of cookie data via HTTP headers. As an added precauttion when you create and get your cookie name/value data you can use the escape and unescape functions respectively. These will convert and unconvert chracters that are not text or numbers into the hexadecimal equivalent of their character in the Latin-1 character set, preceded by a % character.
Once you’ve created your cookie string, you have to store it in the browser’s cookie jar. Even though document.cookie is really just one string, it exhibits special behavior when JavaScript tries to write a cookie to it. Assigning a cookie string to document.cookie does not overwrite the entire property, as it would for a normal string. Instead, the cookie string is added to document.cookie.
If the cookie name already exists, the new value automatically replaces the current one:
document.cookie = theCookie;
Your data is now a cookie! Imagine that document.cookie was originally:
fur=blue; food=biscuts; name=Cookie_Monste
Now, it's:
fur=blue; food=biscuts; name=Cookie_Monster; login=choc_chip
You can only add one cookie at a time, so even though you can replicate the cookie-semicolon-cookie syntax, you cannot concatenate a number of cookie strings together and add them to document.cookie in one go.
Reading a Cookie
It’s no good writing a cookie unless you can access it again. The browser automatically fills document.cookie with all the valid cookies for the current domain, so there’s no chance that you’ll read something you’re not meant to.
There’s nothing glamorous about getting cookies out of document.cookie, you have to parse the string yourself and collect your own values. But, once you understand the syntax of the cookie property, it’s fairly easy to break the process using a few indexOf string method calls. This handy function was found in Chapter 11 of the latest edition of Beginning JavaScript.
function getCookie(name) { var value = document.cookie; var startsAt = cookieValue.indexOf(" " + name + "="); if (startsAt == -1) { startsAt = value.indexOf(name + "="); } if (startsAt == -1) { value = null; } else { startsAt = value.indexOf("=", startsAt) + 1; var endsAt = value.indexOf(";", startsAt); if (endsAt = -1) { endsAt = value.length; } value = value.substring(startsAt, endsAt); } return value; }
var monsterName = getCookie("name");
The value of the variable monsterName is now "Cookie_Monster".
So you can use this simple example to see it in action and download (.zip) if you want too.
