Understanding JavaScript Cookies

Revision as of 19:43, 13 June 2007 by Neil (Talk | contribs)

Revision as of 19:43, 13 June 2007 by Neil (Talk | contribs)

PreviousTable of ContentsNext
Building Forms with JavaScriptBuilding Forms with JavaScriptUnderstanding Cascading Style Sheets (CSS)


The word cookie is one of those technological terms where the name does nothing to convey what the feature actually does. It is commonly believed that even the people at Netscape responsible for devising and implementing cookies didn't really have a valid 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 visitor browsing your web site site. Before you get carried away with dreams of secretly moving all those music and image files clogging your hard drive onto the disks of your site visitors you first need to understand some limitations.

Firstly, a cookie can only hold string based 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 cookie. 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 following settings can be omitted from the cookies if they are not required.

Cookie Expiration Setting

The optional 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 originally 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

Similar 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, a cookie created by a web page residing on www.techotopia.com 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 setting.

Creating a Cookie

Now that we have an understanding of what cookies are and how they are structured we can now look at 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 system:

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


function writeCookie( )
{
        var name = document.orderForm.nameField.value; // Get the user's name
        document.cookie = "yourName=" + name; // Create the cookie
}

</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 that 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 = to extract just the value (see JavaScript String Object). For example:

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

With this in mind we can update our example to read the cookie and display the value assigned to it:

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


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

function readCookie( )
{
        if (document.cookie != "") //make sure the cookie exists
        {
                var yourName = document.cookie.split("=")[1]; //Get the value from the name=value pair
                document.write ("Hello, " + yourName);
        }
}
</script>
</head>

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

</body>
</html>

Removing a Cookie by Setting the Expiration Date

The only way to remove a cookie from a client system is to set the expiration date of the cookie to a date that has already passed. To do this simply use the JavaScript Date Object to get today's date, set that Date back a month or so and then re-write the cookie using that revised date:

var expirationDate = new Date;
expirationDate.setMonth(expirationDate.getMonth()-1);

document.cookie = "yourName=expired; expires=" + expirationDate.toGMTString();