Using Cookies With JavaScript

Store and retrieve persistent data with cookies in JavaScript.

Big Brother Is Watching

In your travels across the Web, I'm sure you've experienced Web sites that seem to know you only too well, displaying your name and email address when you visit them and (in some cases) even remembering the pages you visited the last time you were there. Before you allow your paranoia full rein, though, let me tell you that you probably provided the information yourself to the site in some previous visit, and what you see when you return is merely the results of your own actions, reprocessed for a better visitor experience.

So how do they do it? Well, most of these sites save personal information, such as your name and email address, in files on your hard drive, and read these files every time you re-visit the site. These files are known as "cookies", and they're a simple and easy way to add personalization features to your site. Cookies can also be used to record information about your activities on a particular site; however, they can only be read by the site that created them.

If you have a Web site which caters to a large number of visitors, think of how beneficial similar technology could be to you. You could recognize frequent visitors and greet them by name, "remember" the pages they browsed on their last visit and pop up recommendations for similar content, personalize their experience so that they see your Web site in their favourite colours or layout...the possibilities are endless. And over the course of this article, I'm going to get you started down this particular road, by showing you how to read and write cookies using JavaScript, my favourite language for client-side scripting.

Caveat Emptor

Before you start using cookies, there are a few things you should be aware of:

  • Cookie technology has been supported correctly since Netscape Navigator 2.0. Internet Explorer users should, however, only use cookie technology on platforms supporting Internet Explorer 4.0 or better, due to errors in the cookie-handling routines of earlier versions.

  • Since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, if data persistence is an important feature of your Web site, have a backup plan (such as server-side cookies or sessions) ready as well.

  • A single domain cannot set more than twenty cookies. A single cookie cannot exceed 4 KB in size. The maximum number of cookies that may be set is 300.

Now, with the caveats out of the way, let's take a look at the ingredients that make up a cookie.

  1. The first element in a cookie is a "name" attribute. Here, the "name" is a string used to identify the cookie (akin to a variable name), followed by the data to be stored in the cookie. This variable-value pair is required; you can't bake a cookie without it. For example,
email=me@some.domain.com
  1. A cookie can also contain an "expires" attribute, which specifies how long the cookie is valid for. For example,
expires=Fri, 30-Jan-2004 12:00:00 GMT

Setting this element to a date in the past will usually cause the browser to delete the cookie.

  1. You can also add a "path" attribute to a cookie - this states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root
path=/

to ensure that the data in the cookie is available to all the scripts on the site.

  1. The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional, and might look like this:
domain=somedomain.com
  1. Finally, the "secure" attribute is a Boolean flag indicating whether a secure HTTP connection is required between the client and server to read the data in the cookie. Usually, this is toggled off.

As noted previously, only the first attribute is required; the rest are all optional. If you're using them, remember to separate them with semi-colons, as in the example below:

document.cookie = "name=Joe; path=/; domain=my.site.com; secure";

Now, let's look at writing some code to create a cookie.

What's In A Name?

It's not very difficult to create custom cookie-handling code - after all, all you're really doing is parsing and manipulating a set of values in an encoded string. JavaScript makes it even easier by exposing a "document.cookie" element that does most of the dirty work for you - all you need to do is give it the cookie data to be written. Consider the following example, which illustrates:

<html>
<head>

<script language = "JavaScript">
<!-- start hiding
function writeCookie()
{

    // ask for input
    var name = prompt("What's your name?", "");

    // set expiry date
    var d = new Date("January 31, 2004");
    var cd = d.toGMTString();

    // set cookie parameters
    var c = "username=" + escape(name) + ";expires=" + cd;

    // write cookie
    document.cookie = c;
}

// stop hiding -->
</script>

</head>

<body onLoad="writeCookie()">
</body>

</html>

Most of this is pretty simple - the prompt() method takes care of popping up a box for user input, and the corresponding value is encoded into the cookie string for storage. Similarly, a Date object is instantiated with the cookie's expiry date, converted to the requisite format using the Date object's toGMTString() method and the resulting value is added to the cookie string as part of the "expires" attribute explained earlier. Once the cookie string is ready, the "document.cookie" property takes care of writing it to a file.

Now, try running the code above in your browser. You should see an input box. Enter your name into the box. The value you entered into the box should now be saved as a cookie to your hard drive. If you're the suspicious type, verify this by looking in your browser's cookies directory - you should see a cookie with contents like this:

username
Guru
localhost/cookies/
0
4249743488
29612272
2610381856
29612264

Cookie-Cutter Code

Now, that was pretty simple - but there's more than one way to skin a cat. If you're in a rush and don't have too much time to spend on implementing a custom cookie library, the Web throws up a number of interesting public-domain libraries which are powerful, stable and easy to use.

The best-known of these public-domain cookie libraries is the one created by Bill Dortch in 1996, and used extensively in many sites on account of its rich features and overall stability. Coincidentally, this is also the library I plan to use throughout the rest of this tutorial, so drop by and download a copy before reading any further.

Once you've got yourself a copy of the library, copy it to your development area, and create the following simple HTML document (remember to use the correct path to the library when linking to it in the JavaScript tags):

<html>
<head>
<script language="JavaScript" src="cookieLibrary.js"></script>
<script language="JavaScript" type="text/javascript">
function writeName()
{
    // get user input from form field
    var user = document.forms[0].elements[0].value;

    // calculate expiry date 1 hour from now
    var d = new Date();
    d.setTime(d.getTime() + (60 * 60 * 1000));

    // write value to cookie
    SetCookie("username", user, d);
    alert("Data written successfully");
}
</script>
</head>

<body>
<form>

Enter your name
<input type="text" name="username" size="10">
<input type="button" onClick="javascript:writeName()" value="Save!">
</form>

</body>
</html>

With the Bill Dortch library, setting a cookie is as simple as calling the SetCookie() function with appropriate arguments. The first two of these arguments are the mandatory name and value parameters - these must be set for the cookie to be valid. For persistent cookies, you would also follow these two arguments with an expiry date set to 60 minutes ahead of current time (60 minutes 60 seconds 1000 milliseconds); this will ensure that the cookie is saved to the hard drive and remains valid for 1 hour. For non-persistent (session) cookies, simply omit this expiry date.

Here too, once you've entered your name into the form and hit the "Save!" button, your cookie will be saved to disk in your browser's cookies directory. If you look at the code for the SetCookie() function, you'll see that internally, it does pretty much the same thing you manually did in the example on the previous page.

Running The Numbers

Now, that takes care of writing a cookie. But how about reading back the data you stored in it?

Fortunately, the Bill Dortch library has you covered on that front as well, with its GetCookie() function. To illustrate, consider the following example, which checks for a cookie and retrieves a value from it for display if available:

<html>
<head>
<script language="JavaScript" src="cookieLibrary.js"></script>
<script language="JavaScript" type="text/javascript">
if (GetCookie("username"))
{
    alert("Welcome back, " + GetCookie("username"));
}
</script>
</head>

<body>
</body>

</html>

Here, when the page loads, the GetCookie() function will check to see if a cookie named "username" exists on the client for the specified domain/path combination. If it does, it will be retrieved, the value stored within it will be read, and an alert box will be shown with a welcome message.

Let's look at another example, this one tracking the number of visits that the user has made to the particular Web page:

<html>
<head>
<script language="JavaScript" src="cookieLibrary.js"></script>
<script language="JavaScript">

// check to see if cookie exists
// if not, this is first visit
if(GetCookie("visits") == null)
{
    var visitCount = 1
}
// else this is second or greater visit
// retrieve last counted value and add 1
else
{
    visitCount = parseInt(GetCookie("visits"))+1
}

// set expiry date for 1 year from now
var d = new Date();
d.setDate(d.getDate() + 365);

// update cookie with new count
SetCookie("visits", visitCount, d);

// display visit counter
document.write("This is visit " + visitCount)
</script>

</head>

<body>
</body>

</html>

Here, as before, I use an "if" test to check whether a cookie already exists to track the number of visits. If it does, I use the GetCookie() function to retrieve the value; if it does not, I assume this is the first visit to the page and initialize the counter to 1. The value of the counter is then updated (if necessary) and written back to the cookie in readiness for the next visit.

Speaking Native

So that takes care of writing cookies, and then reading the values back. Now, how about a composite example that you can actually use?

In this next example, I'll assume a multi-lingual Web site, where the user has a choice of viewing the content in either French or English. The first time the user visits the site, (s)he is permitted to select one of the two languages. This choice is stored in a cookie, so that on the next visit, the client is automatically redirected to the chosen language without requiring the user to re-select a language.

<html>
<head>
<script language="JavaScript" src="cookieLibrary.js"></script>
<script language="JavaScript">
// check to see if cookie exists
// if yes, redirect to language page
if (GetCookie("lang") == "EN")
{
    document.location.href="index.en.html";
}
else if (GetCookie("lang") == "FR")
{
    document.location.href="index.fr.html";
}

// function to write selected language to cookie
function lang(l)
{
    // set expiry date for 1 year from now
    var d = new Date();
    d.setDate(d.getDate() + 365);

    // write cookie
    SetCookie("lang", l, d);

    // take user to appropriate language page
    if (l == "EN")
    {
        document.location.href="index.en.html";
    }
    else if (l == "FR")
    {
        document.location.href="index.fr.html";
    }

}
</script>

</head>

<body>

<h2>
Please select your language:
<ul>
<li><a href="javascript:lang('EN');">English</a>
<li><a href="javascript:lang('FR');">French</a>
</ul>
</h2>

</body>
</html>

That was simple enough. When the user visits the page, the code first checks to see if a cookie with the selected language already exists. If it does, the browser is automatically redirected to pages in that language. If no cookie exists, it implies that the user has not selected a language, and so a language choice is displayed. The language selected is then written to a cookie in preparation for the next visit.

Dinner Time

And that's about it for this tutorial. Over the last few pages, I gave you a crash course in reading and writing cookies using JavaScript. I explained what cookies were, dissected the innards of a cookie and showed you what they contain, and then took you through the process of reading and writing a cookie with the "document.cookie" property, and with the Bill Dortch cookie library. Finally, I wrapped things up with an example of how you could use cookies in a real-world environment, to personalize a Web site for your users by automatically selecting their favourite language for them.

Of course, this is just the tip of the iceberg. You can do a lot more with cookies - take a look at the following links for more information:

The Netscape cookie specification, at http://www.netscape.com/newsref/std/cookie_spec.html

Bill Dortch's cookie library, at http://www.webwoman.biz/articles/Cookies/cookie.txt

JavaScript cookie applications, at http://javascript.internet.com/cookies/

More sample cookie applications, at http://members.ozemail.com.au/~dcrombie/cookie.html and http://developer.netscape.com/viewsource/archive/goodman_cookies.html

Detecting cookie support in the client, at http://www.javascriptkit.com/javatutors/cookiedetect.shtml

Sample cookie code and demos, at http://www.cookiecentral.com/

Until next time...be good!

Note: Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!

This article was first published on12 Jan 2004.