Cookies
JavaScript topics covered:

The cookie is a property of the document object. Cookies were invented by Netscape to help designers build web sites that help the user view the web site more effectively. For example, you can allow users to personalize their view of the site by setting the information in a cookie, so next time they visit the page, it is layed out with the information they want to see.


  1. Temporary Cookies are those that are valid while the user is on your web site, when they leave, the cookies are deleted. This type of cookie is useful for gathering information that will be used by other pages.
    Persistent Cookies remain on the user's hard drive even after they leave the site, close their browswer, or shut down their computer. So, when the user comes back, you already have information about them.

    Adding an expiration date to a cookie will keep it from being deleted once the browser is closed, or it can be used to expire a cookie you no longer want to use. When setting an expiration date, the date must be expressed in GMT(Greenwich Mean Time).

  2. Cookies are a great way to gather information, however they do have thier limits:
  3. Now, on to creating cookies! Cookies have 4 properties (name=, expires=,domain=, path=). To create a cookie you need to create a string with "cookieName=value" and move it to the document.cookie property. The other three parameters are optional. If an expiration date is not given, the cookie expires when the visitor exits or quits the web browser. Path and domain information can be added to specify the location of pages that are authorized to retrieve the cookie. If they are not given, the location and domain are assumed.

    Let's use the business card example from a previous class example where we have information for a business card (business name, address, city, state, zip code). Each piece of information will be saved in the cookie. The example had a business card that looked like this
    Dogs and Cats
    121 Tail Wag Way
    St Louis, MO 63121
    

  4. Yippy! We created a cookie with 5 pieces of information (businessName, businessAddr, businessCity, businessState, businessZip) about the business card. So, how do we get the information back out? It's pretty simple, put the value of the cookie in a variable and write the variable to the screen.
     <script language="JavaScript">
     function printBusinessCard(){
     var myCookie = document.cookie;
     document.write(myCookie);
     }
     </script>
      
     BusinessCard=Dogs%20and%20Cats%3B121%20Tail%20Wag%20Way%3BSt%20Louis%3BMO%3B63121
     
    Eek!! The variable myCookie contains all the information previously stored in the cookie, however it doesn't look quite right. Notice the spaces are %20 and the semi-colons are %3B. When getting the information back out of a cookie you want to convert the hexadecimal data back to ASCII character set . To do this use unescape()
     <script language="JavaScript">
     function printBusinessCard(){
     var myCookie = unescape(document.cookie);
     document.write(myCookie);
      }
     </script>
      
     
    BusinessName=Dogs and Cats;121 Tail Wag Way;St Louis;MO;63121
     

    The printBusinessCard() function is great if we only have one cookie with the business card information. However, if you have more than one cookie, the function above would bring back all of the cookies seperating each by a "; ". If you had two business cards, (card1, card2) and some other cookie, the command unscape(document.cookie) would look like this:

     
    card1=businessName;businessAddr;businessCity;businessState;businessZip; card2=businessName;
    businessAddr;businessCity;businessState;businessZip; nextcookie=value
     
    Click here to see the example

    So, it would be best to create a function that just brings back the business card we want to work with. We know that each cookie was created with "cookieName=value" and each cookie is seperated by a semi-colon and a space "; ". In our example we have two cookies (Card1=value, Card2=value). The value contains the 5 pieces of information about our business card and each is seperated by a semi-colon ";". We could write a function that accepts the name of the cookie and brings back the cookie value.

     
    function getCard(cardName){
    	var cardValue = document.cookie;
    	var cardStartsAt = cardValue.indexOf(" " + cardName + "=");
    	if (cardStartsAt == -1)
    		cardStartsAt = cardValue.indexOf(cardName + "=");
    	if (cardStartsAt == -1)
    		cardValue=null;
    	else
    	{
    		cardStartsAt = cardValue.indexOf("=", cardStartsAt)+1;
    		var cardEndsAt = cardValue.indexOf(";",cardStartsAt);
    
    		if (cardEndsAt == -1){
    			cardEndsAt = cardValue.length;
    		}	
    		cardValue = unescape(cardValue.substring(cardStartsAt,cardEndsAt));
    	}
    	return cardValue;
    	
    } //end function
    
     

    So, let's bring back the value of Card2. It should look like this:

     Bird Brain Co.;10 Fly Away Trails;Bird;CO;78501
    Click here to see the example

  5. There are several ways we can process the cookie string.
    1. Notice that between each piece of information about the business card we put a ";". We could write a function that would parse through the string looking for the ";"and pull out the information.
      function printCard(cookieString){
      document.writeln("businessCard="+cookieString);
      var strLen, strValue; 
      var strLen = cookieString.length;
      	//parse data
      	while (strLen > 0){
      		i = cookieString.indexOf(";");
      		if (i>0){
      			//get the value
      			strValue = cookieString.substring(0,i);
      			document.writeln("strValue:" + strValue);
      			cookieString = cookieString.substring((cookieString.indexOf(";")+1));
      			strLen = cookieString.length;
      		}
      		
      		else {
      			//myCookie contains the last value
      			strLen = 0;
      			document.writeln("strValue:" + cookieString);
      
      		}
      	} //end while
      } //end function
      
      businessCard=Dogs%20and%20Cats%3B121%20Tail%20Wag%20Way%3BSt%20Louis%3BMO%3B63121
      strValue:Dogs and Cats
      strValue:121 Tail Wag Way
      strValue:St Louis
      strValue:MO
      strValue:63121
      
      Click here to see the example

    2. Notice that between each value there is a ";". We can use the array.split() method to break the cookie apart at each ";".
      <script language="JavaScript">
      function printCard(cookieString){
      	document.write("businessCard:" + cookieString);
      	var cookieArray = cookieString.split(";");
      	for (i=0;ibusinessCard[" + i + "]=" + cookieArray[i]);
      }
      </script>		
        
      businessCard:Bird Brain Co.;10 Fly Away Trails;Bird;CO;78501
      businessCard[0]=Bird Brain Co.
      businessCard[1]=10 Fly Away Trails
      businessCard[2]=Bird
      businessCard[3]=CO
      businessCard[4]=78501
      
      Click here to see the example

  6. Now that we have created a cookie or two, how can you delete them? To delete a cookie you need to set it's expiration date to some time in the past, like last year.
    function deleteCard(theCard){
    		var expirationDate = new Date();
    		//set expiration date to last year
    		expirationDate.setFullYear(expiresDate.getFullYear() - 1);
    		var temp = theCard + "=; expires=" + expirationDate.toGMTString() + ";";
    		document.cookie = temp;
    }
    
    Click here to see the example