Understanding JavaScript Cookies

Revision as of 15:14, 18 May 2007 by Neil (Talk | contribs) (Cookie ''domain'' Setting)

Revision as of 15:14, 18 May 2007 by Neil (Talk | contribs) (Cookie ''domain'' Setting)

The word cookie is one of those technological terms where the name doe snothing to convery what the feature actaully does. It is commonly believed that even the people at Netscape responsible for devising and implementing cookies in JavaScript didn't really have a vlaid reason for selecting the name. Questionable naming aside, JavaScript cookies are actually an extremely powerful feature.

What is a JavaScript Cookie?

Cookies allow you to store information on the computer of the person browsing your site. Before you get carried away with dreams of secretly storing all those music files and pictures clogging your hard drive on the disks of your site visitors you first need to understand some limitations. Firstly, a cookie can only hold name/value pairs (i.e name=value settings). You cannot store binary data in a cookie. Secondly, cookies can be a maximum of 4kb in size each. Finally, a single server or domain can only store a total of 20 cookies per user browser.

Another common limitation of cookies is that browsers can be configured to turn off support for cookies. If you design a web site that relies on cookies being supppoted by the user's browser there is the possibility that your site will fail to function for a certain percentage of your visitors.

Despite the limitations outlined above, cookies provide an excellent way to maintain state on the clients browser. For example you might want to store information in a cookie so that when a user returns to your site they can pick up where they left off (perhaps partway through completing an all important purchase in an online shopping cart).

The Structure of a Cookie

Cookies are created using the cookie property of the Document object. The format of a cookies is as follows:

name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain

Cookie Name / Value Pair

The first section of the cookie defines the name of the cookie and the value assigned to the cookies. Both the name and value settings can be anything you choose to use. For example you might want save a user's currency preference - currency=USDollars. This is the only section of the cookie that is mandatory. The followingf settings can be omitted from the cookies if they are not requied.

Cookie Expiration Setting

The option expires= section specifies the date on which the cookie should expire. The JavaScript Date Object can be used to obtain and manipulate dates for this purpose.

For example to set a cookie to expire in 6 months time:

var expirationDate = new Date;
expirationDate.setMonth(expirationDate.getMonth()+6)

Cookie path Setting

The path= setting allows a URL to be stored in the cookie. By default, cookies are accessible only to web pages in the same directory as the web page which origianlly created the cookie. For example, if the cookie was created when the user loaded http://www.techotopia.com/intro/index.html that cookie will be accessible to any other pages in the /intro directory, but not to pages in /navigation. By specifying path=/navigation this limitation is removed.

Cookie domain Setting

Similarly to the path setting, cookies are only accessible to web pages residing on the server domain from which the cookie was originally created. For example acookie created by a web page residing on www.techotopia.org is not, by default, accessible to a web page hosted on www.linuxtopia.org. Access to the cookie from web pages on linuxtopia.org can be enabled with a domain=linxutopia.org.

Creating a Cookie

Now that we have an understanding of what cookies are and how theya re structured we can now looka t how to create one. As mentioned previously in this chapter cookies are created using the cookie property of the JavaScript Document object. In the following example we will prompt the user for their name and then write that information to a cookie on their computer:

<html>
<head>
<title>JavaScript Cookie Example</title>
<script language=javascript type="text/javascript">


function writeCookie( )
{
        name = document.orderForm.nameField.value;
        document.cookie = "yourName=" + name;
}

</script>
</head>

<body>
<form action="" name="orderForm">
Enter your name: <input type="TEXT" name="nameField"/>
<input type="BUTTON" value="Write Cookie" onClick="writeCookie()" />
</form>

</body>
</html>

Reading a Cookie

Once a cookie is written we can then read tha cookie back. We will now extend our example to add a "Read Cookie" button which will read the value of the cookie and write it out to the browser document. Note that the value/pair of the cookie is actually a JavaScript String object so we can use the String split() method to divide the name=value at the = and extract just the value (see JavaScript String Object). For example:

var yourName = document.cookie.split("=")[1];