Register for EarthWeb's Million Dollar Sweepstakes!
home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Platinum Edition Using HTML 4, XML, and Java 1.2
(Publisher: Macmillan Computer Publishing)
Author(s): Eric Ladd
ISBN: 078971759x
Publication Date: 11/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Listing 22.2 FavList.htm (excerpt)—Adding Cookies Is Easy with JavaScript


// SetCookieEZ - Quickly sets a cookie which will last until the
//               user shuts down his browser
//
function SetCookieEZ(name,value) {
   document.cookie = name + “=” + escape(value);
}

Notice that the value is encoded using the JavaScript escape function. If there were a semicolon in the value string itself, it might prevent you from achieving the expected results. Using the escape function eliminates this problem.

Also notice that the document.cookie property works rather differently from most other properties. In most other cases, using the assignment operator (=) causes the existing property value to be completely overwritten with the new value. This is not the case with the cookie property. With cookies, each new name you assign is added to the active list of cookies. If you assign the same name twice, the second assignment replaces the first.

Some exceptions exist to this last statement, but these are explained in the section “Path” later in this chapter.

Expiration Date The expires=date tells the browser how long the cookie will last. The cookie specification page at Netscape states that dates are in the form of

Wdy, DD-Mon-YY HH:MM:SS GMT

Here’s an example:

Mon, 08-Jul-96 03:18:20 GMT

This format is based on Internet RFC 822, which you can find at http://www.w3.org/hypertext/WWW/Protocols/rfc822/#z28.

The only difference between RFC 822 and the Netscape implementation is that in Netscape Navigator, the expiration date must end with GMT (Greenwich Mean Time). Happily, the JavaScript language provides a function to do just that. By using the toGMTString() function, you can set cookies to expire in the near or distant future.


Even though the date produced by the toGMTString() function doesn’t match the Netscape specification, it still works under JavaScript.

If the expiration date isn’t specified, the cookie remains in effect until the browser is shut down.

The following is a code segment that sets a cookie to expire in one week (where one week equals 7 days/week times 24 hours/day times 60 minutes/hour times 60 seconds/minute times 1000 milliseconds/second):

var name=“foo”;
var value=“bar”;
var oneWeek = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + oneWeek);
document.cookie = name + “=” + escape(value) + “; expires=” +
                  expDate.toGMTString();

Deleting a Cookie To delete a cookie, set the expiration date to some time in the past—how far in the past doesn’t generally matter. To be on the safe side, a few days ago should work fine. The following is a routine to delete a cookie, shown in Listing 22.3.

Listing 22.3 FavList.htm (excerpt)—Use the Cookie Expiration Date to Delete an Unwanted Cookie


// ClearCookie  - Removes a cookie by setting an expiration date
//                three days in the past
//
function ClearCookie(name) {
   var ThreeDays = 3 * 24 * 60 * 60 * 1000;
   var expDate = new Date();
   expDate.setTime(expDate.getTime() - ThreeDays);
   document.cookie = name + “=ImOutOfHere; expires=” +
                     expDate.toGMTString();
}

When deleting cookies, it doesn’t matter what you use for the cookie value—any value will do.


CAUTION:  

Some versions of Netscape do a poor job of converting times to GMT. Some common JavaScript functions for deleting a cookie consider the past to be one millisecond behind the current time. Although this is usually true, it doesn’t work on all platforms. To be on the safe side, use a few days in the past to expire cookies.


Path By default, cookies are available to other Web pages within the same directory as the page on which they were created. The Path parameter enables a cookie to be made available to pages in other directories. If the value of the Path parameter is a substring of a page’s URL, cookies created with that path are available to that page. You could create a cookie, for example, with the following command:

document.cookie = “foo=bar1; path=/javascript”;

This would make the cookie foo available to every page in the javascript directory and all those directories beneath it. If, instead, the command looked like this:

document.cookie = “foo=bar2; path=/javascript/sam”;

the cookie would be available to sample1.html, sample2.html, sammy.exe, and so on.

Finally, to make the cookie available to everyone on your server, use the following command:

document.cookie = “foo=bar3; path=/”;

What happens when a browser has multiple cookies on different paths but with the same name? Which one wins?

Actually, they all do. When this situation arises, it is possible to have two or more cookies with the same name but with different values. If a page issued all the commands listed previously, for example, its cookie string would look like the following:

foo=bar3; foo=bar2; foo=bar1

To help be aware of this situation, you might want to write a routine to count the number of cookie values associated with a cookie name. It might look like this:

function GetCookieCount(name) {
   var result = 0;
   var myCookie = “ ” + document.cookie + “;”;
   var searchName = “ ” + name + “=”;
   var nameLength = searchName.length;
   var startOfCookie = myCookie.indexOf(searchName)
   while (startOfCookie != -1) {
      result += 1;
      startOfCookie = myCookie.indexOf(searchName,startOfCookie + nameLength);
   }
   return result;
}


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.