Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Using Cookies

You've learned quite a bit in your 24-hour exploration of JavaScript. Just to prove that there's more to learn if you choose, here's a final lesson on a useful JavaScript feature for advanced scripts.

Cookies allow you to store one or more variables on the user's computer. This allows your Web pages to remember key information—for example, a username or the current score in an online game.

Unlike regular JavaScript variables, cookies are persistent—once you've set one, it will be available to your script each time the same user views your page until the cookie reaches the expiration date you've set. They're a great way to recognize previous visitors or to let the user avoid typing the same information over and over.

Setting a Cookie

Cookies are specific to a single Web page. You can set one or more cookies using the document.cookie property. To set a cookie, you just need to specify a name for the cookie, a value, and an expiration date:

name=window.prompt("Please enter your name","");
d = new Date();
d.setFullYear(d.getFullYear() + 1);
expires="expires=" + d.toGMTString();
document.cookie="Username=" + name + "; " + expires;

This example prompts for a name and sets a cookie called Username to store the name. The d variable is used to store the expiration date, which is set one year in the future. If the user name is Fred, the cookie value will look something like this:

Username=Fred; expires= Fri, 25 Apr 2004 08:14:05 UTC

To delete a cookie, you simply re-set it using an expiration date in the past. You can also set an existing cookie to a new value.

Reading a Cookie

As you might have guessed, reading a cookie is as simple as reading the document.cookie property. However, this property includes all the cookies for the current page—since there might be more than one, you need to use some string functions to extract the cookie you want. The following example finds the Username cookie's value:

cookies=document.cookie;
startpos=cookies.indexOf("Username") + 9;
endpos=cookies.indexOf("",startpos);
if (endpos==-1) endpos=cookies.length;
name=cookies.substring(startpos,endpos);

This code uses the indexOf method to find the position of the Username= string that begins the cookie. It adds nine characters to skip over Username=, and this is the start position of the value.

The end position is calculated by looking for a semicolon after the start position. Some browsers don't include the semicolon when there's only one cookie, so it sets the end position to the end of the document.cookie value if there isn't a semicolon.

Having calculated the start and end positions for the value, the final line of this example uses the substring method to read the value for the Username cookie.

Putting It All Together

Now that you've learned how to set a cookie and how to read the value of a cookie, you can put them together to make a simple example. This example displays a personalized welcome message when it loads. The first time you load it, it prompts for a name and stores the name in a cookie.

The second time you load this example, it uses the name stored in the cookie and doesn't need to prompt for a name. Listing 24.1 shows the complete example.

Example 24.1. Complete Cookie Personalized Welcome Message

<html>
<head><title>Cookie Example</title>
</head>
<body>
<h1> Cookie Example</h1>
<script language="javascript1.1" type="text/javascript1.1">
cookies=document.cookie;
startpos=cookies.indexOf("Username") + 9;
   if (startpos<9) {
      // No cookie set
      name=window.prompt("Please enter your name","");
      d = new Date();
      d.setFullYear(d.getFullYear() + 1);
      expires="expires=" + d.toGMTString();
      document.cookie="Username=" + name + "; " + expires;
      document.write("<h2>Welcome, " + name + "!</h2>");
   } else {
      // Cookie was found
      endpos=cookies.indexOf("",startpos);
      if (endpos==-1) endpos=cookies.length;
      name=cookies.substring(startpos,endpos);
   document.write("<h2>Welcome Back, " + name + "!</h2>");
   }
</script>
<p>This example's script uses a cookie to save
the user name. If no cookie is set, it prompts for
a name.</p>
</body>
</html>

To test this example, load it into a browser—it should work with Netscape 4 or later or Internet Explorer 4 or later. You'll be prompted for a name, and the next time you load the page it will welcome you back using the name stored in the document's cookie. Figure 24.1 shows the example in action.

24fig01.jpg

Figure 24.1 The cookie example in action.

Share ThisShare This

Informit Network