Baking JavaScript Cookies

[ LiB ]

Baking JavaScript Cookies

Cookies are small text strings that you can store on the computers of people that visit your Web site. You can use cookies to store information about visitor activity or preferences. Later, when a visitor returns to your Web site, you can retrieve this information and use it to present customized content. For example, you might use cookies to store and retrieve visitor's names or their preferred color settings.

Cookies are used by virtually every major Web site on the Internet today. Cookies are stored in plain text files on the user 's computer. Cookie technology is very limited. Cookies cannot be used to plant viruses on a visitor's computer, nor can they be used to store large amounts of data. In fact, cookies are limited to 4KB in size. Both Internet Explorer and Netscape Communicator limit the number of cookies that can be stored on a computer to 300. In addition, no one Web site is permitted to store more than 20 cookies on a visitor's computer. As a result, the total number of cookies that can be stored on any computer will take up no more than 1.2MB of disk space.


It is important to understand that your JavaScripts cannot actually store cookies directly on a visitor's computer. Instead, the cookies that your scripts create are stored in the browser's cache.Whether they are ultimately saved on the visitor's computer depends on whether or not the browser has been configured to save them.

Both Internet Explorer and Netscape Communicator provide the capability to block cookies from being stored on computers. However, most users quickly find that disabling cookies is impractical because too many Web sites depend on them in order to provide their content.

Cookies can be retrieved only by the Web site that created them. Therefore any cookie you create is safe from view of other Web sites. This provides a degree of security. However, since cookies are stored as plain text files, they are easily read by anybody working on the computer where they are stored. This makes cookies inappropriate for storing highly sensitive information such as passwords or credit card numbers .



To learn more than you would ever want to know about cookies,visit

Understanding Cookie Syntax

To create and retrieve cookies, you need to know how to work with the document object's cookie property. By assigning a value to the document.cookie property, you create a new cookie. For example, the following statement defines a cookie that stores the visitor's name :

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

The expires field is required and tells the browser how long to store the cookie before deleting it. If you forget to add this field, the cookie expires as soon as the current session ends.

In a similar fashion, you can retrieve the cookie the next time the visitor loads your Web page, using the following statement:

 myCookie = document.cookie; 

In the examples that follow, I will show you how to create and retrieve your first JavaScript cookie.

Creating a Cookie

This first cookie example displays a form that asks visitors to type their names. It then creates a cookie that includes the visitor's name and an expiration date of one month from the current date.


This very simple example does not include logic to first make sure that the visitor does not already have a cookie from you before bothering to ask for his name.The example also does not contain logic to check whether the cookie is about to expire so that it can replace it with a new one. I will leave that code to you to devise .

 <HTML>   <HEAD>     <TITLE>Script 5.1 - Baking your first cookie</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements          expirationDate = new Date;         expirationDate.setMonth(expirationDate.getMonth() + 1);         function BakeTheCookie(name) {            document.cookie = "name=" + nam e + ";expires=" + expirationDate.toGMTString();         }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY>     <H3>Cookie Information Collector</H3>     <FORM NAME="myForm">       <B>What is your name? </B>       <INPUT TYPE="text" NAME="visitorName">       <INPUT NAME="myButton" TYPE="button" VALUE="Save Cookie"          onClick="BakeTheCookie(document.myForm.visitorName. value)">     </FORM>   </BODY> </HTML> 

This example contains a script in the head section. The first thing the script does is define an object called expirationDate . Next it sets the expiration date for the cookie, using the Date object's setMonth() method to add one month to the current date:

 expirationDate = new Date; expirationDate.setMonth(expirationDate.getMonth() + 1); 

The logic to "bake" the cookie is located in a function named BakeTheCookie() . This function accepts the name of the visitor as an argument:

 function BakeTheCookie(name) {   document.cookie = "name=" + name + ";expires=" + expirationDate.toGMTString(); } 

The rest of the example is a form that collects the visitor's name and then calls the BakeTheCookie() function.


Figure 5.1 demonstrates what the example looks like when it is first loaded into your browser.

Figure 5.1. You can use a cookie to store information about your visitors that you can reuse every time they visit your Web site.


Viewing Your Cookie

Okay, so you have baked your cookie and saved it on your visitor's computer. What next? The answer isnot much. You just wait for the visitor to return. When the visitor returns, you can check to see whether he has one of your cookies, as demonstrated in the following example.


In actual practice, you will want to write a script that combines the cookie logic of this and the previous example so that you first check to see whether the user has one of your cookies before you assign another cookie.

 <HTML>   <HEAD>     <TITLE>Script 5.2 - Retrieving your cookie</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       function CookieCheck() {         visitorName = "";         cookieName = "";        if (document.cookie != "") {         cookieName = document.cookie.split("=")[0];         visitorName = document.cookie.split("=")[1];          window.alert("cookieName = " + cookieName + "\nCookie Contents = " + visitorName);        }        else {          window.alert("Your cookie was not found!");        }      }     // End hiding JavaScript statements -->     </SCRIPT>    </HEAD>   <BODY onLoad="CookieCheck()">   </BODY> </HTML> 

The logic that retrieves your cookie is located in a function named CookieCheck() , which is located in a script embedded in the HTML page's head section. The function is called by the onLoad event in the <BODY> tag.

The first thing the script does is check to see whether or not the visitor already has one of your cookies:

 if (document.cookie != "") 

If the visitor does not have one of your cookies, the document object's alert() method is used to display a pop-up dialog box stating that a cookie was not found. However, if a cookie was found, the script retrieves the value of the cookie using the cookie object's split() method. The split() method breaks the cookie into fields. The first statement sets a variable named cookieName equal to the name the cookie was saved as. The second statement sets another variable named visitorName to the name that is stored in the cookie.

 cookieName = document.cookie.split("=")[0]; visitorName = document.cookie.split("=")[1]; 

The script then uses the window object's alert() method to display the contents of the cookie:

 window.alert("cookieName = " + cookieName + "\nCookie Contents = " + visitorName); 


Although this example shows you how to retrieve and display your cookie, a more effective use of this information might be to display a welcome message that greets the visitor by name.

Figure 5.2 demonstrates how the script formats the result when it finds a cookie.

Figure 5.2. By retrieving cookie information, you can avoid having to ask visitors repeatedly for the same information and can greet them by name when they return to your site.


A really good example of how to use cookies when creating your Web site is provided in the On-line Bookmall project presented later in this chapter.

[ LiB ]

Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84 © 2008-2017.
If you may any questions please contact us: