Tutorial 9 - Cookies

Tutorial 8 - Multimedia - Tutorial 10 - Menuing Systems

Cookies are used for information storage that can be read either by the same page on a later viewing, other HTML/JavaScript pages on the same site or by servers. Cookies are stored in a file named cookies.txt in Netscape or in the folder \System\Cookies in MSIE. Some of the many uses of cookies are: tracking visits by a specific client, remembering the last page viewed,shopping basket storage, notifying a user of any recent change to site, user profiling: login, view method, preferences, passing information from one document to another and maintaining state information longer than a session

Required Ingredients for a Cookie

Certain ingredients are required for the correct baking of a cookie from scratch. The following sections of this page provide functions that set reasonable defaults for most applications. But these ingredients can be added as baking parameters if needed by a specialized application.

Name
Used as the identifier as many cookies could be used for different purposes by the same site. Names can't contain semicolon, comma or space. Well behaved calls will verify that the name does not have any of these characters.
Value
The data that is to be saved.
Expires
Last date that the 'value' is valid for. Format is DD-Mon-YY HH:MM:SS UTC
NOTE: MSIE expires after the date, gecko expires on the date. The data is not necessarily removed from the file but it is inaccessable using JavaScript.
Path
Restricts cookie to specific level of a site. Defaults to the level that made the cookie.
Domain
Site specification to restrict access to cookies. Defaults to open.
Secure
If set to 'true', the cookie responds only to a 'secure' server. Defaults to 'false'

Baking a Cookie

BakeCookie is a generic function for creating cookies. It also illustrates how you can have a variable number of parameters for a JavaScript function. The mandatory parameters are the variable name and the value to be stored. Multiple values can be stored in the same cookie by calling the BakeCookie function several times but using a different variable name as the first parameter. This function is written so that optional parameters default to useful values, and the order is predefined as given above in cookie ingredients (ie. expiry [defaults to never], path, domain, security). MSIE stores cookies in \windows\cookies and gecko browsers store cookies in a cookies.txt file (useful debugging note!). Netscape and mozilla share the cookie.txt file in the mozilla profile.

function BakeCookie(name,value) {
   argv=arguments;
   argc=arguments.length;
   expires=(argc>2) ? argv[2] : null;
   path=(argc>3) ? argv[3] : null;
   domain=(argc>4) ? argv[4] : null;
   secure=(argc>5) ? argv[5] : false;
   document.cookie=name+"="+escape(value) +
     ((expires === null) ? "" : ("; expires="+expires.toUTCString())) +
     ((path === null) ? "" : ("; path="+path)) +
     ((domain === null) ? "" : ("; domain="+domain)) +
     ((secure === true) ? "; secure" : "");
}

Eating a Cookie

EatCookie is a generic function that recovers stored cookie information. The only required parameter is the variable name. The returned value is a string value or null if nothing was stored in that variable.

function EatCookie(name) {
   arg=name+"=";
   alen=arg.length;
   clen=document.cookie.length;
   i=0;
   while (i<clen) {
      j=i+alen;
      if (document.cookie.substring(i,j) == arg) {
          return EatCookieVal(j);
          }
      i=document.cookie.indexOf(" ",i) + 1;
      if (i === 0) {break;}
   }
}
function EatCookieVal(offset) {
   endstr=document.cookie.indexOf(";",offset);
   if (endstr == -1) {endstr=document.cookie.length;}
   return unescape(document.cookie.substring(offset,endstr));
}

Tossing a Cookie

TossCookie is a generic function that removes an old cookie value from further use. It relies on the fact that each cookie has an expiry date. By setting that date to one prior to today, the cookie will be eliminated automatically.

function TossCookie(name) {
   ThreeDays = 3*24*60*60*1000; //in millisecounds
   expDate=new Date();
   expDate.setTime(exp.getTime()-ThreeDays);
   document.cookie=name+'=foobar; expires='+expDatetoGMTString();
}

Working Example #1 - Saving a User Preference

One of the most common uses of cookies is saving user preferences for reuse. Our example will use an improved color selector based on the one in tutorial 7 and save its setting. Returning to the page will reset the color to the last setting selected.

function newColor(entry,areaID) { // use DOM only, no geezer browsers
   BakeCookie("colorSet",entry,expDate);
   styleObj=document.getElementById(areaID).style;
   styleObj.background=entry;
}
Background  Aquamarine:
 Burlywood:
 Floralwhite: 
 Goldenrod:  
 Peachpuff:  
 White:   
 

STEP 1: Create an interface such as a form for the color entry. Forms and DHTML has several methods that may be used. Make sure that the element that displays the color has an id attribute.

STEP 2: Add a script element to the document body and initialize a global value for the cookie's expiry date.

   expDate=new Date();
   ThreeDays = 3*24*60*60*1000; //in millisec
   expDate.setTime(exp.getTime()-ThreeDays);

STEP 3: Copy the BakeCookie(), EatCookie(), TossCookie() and newColor() functions into the script.

STEP 4: Set up init function that eats the old cookie if it is there and calls the color setting function. Call this function with the onload attribute in the body element.

function InitCookie(areaID) { // points at color element
   colorSet = null;
   if (!(colorSet = EatCookie("colorSet"))) {colorSet=null;}
   if (colorSet !== null) {newColor(colorSet,areaID);}
}

STEP 5: Add a call from the color setting function to bake a new cookie with any updates.

Working Example #2 - Saving a User 'Agreement'

User agreement to site policy statements are common on corporate sites offering copyright material or corporate property on-line. To perform this kind of customer recording you would first display 'the terms of use' message with a checkbox or radio button for acknowledgement of reading. Some do not display checkbox/button until scrolling has been done, indicating a chance of 'terms' being read. At the acknowledgement, a cookie is created so that the next visit does not show the agreement. Some sites also create a mailto message at this point to record the visitors agreement (ie. documentation for later legal use). Any page that requires the agreement would check for the cookie's existence and if not there redirect the user to the agreement page.

Step 1: Create a form with the 'terms' and buttons for acknowledgement.

Step 2: When 'Agree' button is checked bake a cookie for it.

Step 3: If needed, submit the form as a mailto or to a mail server.

Step 4: Add an eat cookie and if not found then redirect routine to each page on site that requires agreement acknowledgement.

Note that this section is a work in progress. The preceding is an algorithm that will work. The actual code will be developed soon and included.

Tutorial 8 - Multimedia - Tutorial 10 - Menuing Systems

Copyright (c) 2005 by John W. M. Russell