Chapter 13. Remember with Cookies

CONTENTS

CONTENTS>>

  •  What Are Cookies and How Are They Used?
  •  Adding More Attributes
  •  Getting Information and Giving It Back
  •  Summary

What Are Cookies and How Are They Used?

Think of cookies as llttle lumps of data stored on the viewer's hard drive. Cookies are stored as data files in ASCII format, except on Macintosh, where you have a MagicCookie format. The text format precludes viruses being passed through them, and yet cookies provide a convenient and useful way of passing information about the user through the browser.

Cookies are used in a variety of ways. Usually, the designer wants the web page viewer to feel welcomed and focused on those key elements of personal interest. By examining the information on a cookie, the page can respond with the viewer's name and her personal favorites. For example, when I open my web portal page that I use for searches and news, I am greeted with "Welcome Bill!" Then the page shows all of the stocks, news stories, and other interests that I have. The way the page knows who I am is by reading my cookie file.

If you are concerned about personal information being used in the wrong way, a viewer can always delete his cookie file from his drive. If you have Windows OS, just select Start, Search, For Files or Folders. You will find a folder named COOKIES on your drive. You can throw every cookie or the entire folder in the Recycle Bin, if you want to delete them. Alternatively, you can just toss those cookies that you want removed. In my case, I don't want my cookies from the online bookstores deleted, so I keep them. On the other hand, I might have looked at a page with advertising that I don't want any more, so I can delete that cookie. Figure 13.1 shows a typical cookie folder's contents.

Figure 13.1. You can see the contents of all your cookies in text files stored on your Windows PC.

graphics/13fig01.gif

On Macintoshes, use Sherlock to search for MagicCookie. When you find it, you can look at the cookies using your word processor. Netscape stores your cookie file inside the System folder and subfolders within, as shown in Figure 13.2 Be careful if you make any changes to the MagicCookie file on your Mac using your word processor. It's easy to misalign the different cookies and mess up the ones that you want to keep. If you want to view or delete cookies on your Mac or PC using Netscape Navigator, open Edit, Preferences, Advanced, Cookies, View Stored Cookies. You can scroll through your cookies and view or delete individual ones. Using Internet Explorer, you can do the same thing by choosing Edit, Preferences, Receiving Files, Cookies.

Figure 13.2. On the Macintosh, Netscape stores cookies as MagicCookies.

graphics/13fig02.gif

Putting Cookies to Work

As far as JavaScript is concerned, cookies are document objects that can be used to read data through the viewer's browser and write data to the viewer's drive. When you open your browser, part of the document is a cookie; hence, this format can be used to extract or set a cookie:

document.cookie 

When a page is loaded, this line places the cookie in the variable varName:

var varName=document.cookie; 

The general format for setting a cookie is this:

document.cookie=name=value;[expires];[path];[domain];[secure]; 

The cookie's value is set as a name with a value. This format might be a little confusing because of a double assignment of name and value. However, when you get used to it, you can do some creative designs. The other attributes are optional, and they are discussed further in this section.

Creating a Cookie

In its simplest format, creating a cookie provides a name for the cookie and a value. For example, the following script sets a cookie with a name and a value:

<html>  <head>  <style>body {color:orangered} </style>  <script language="JavaScript">  document.cookie="sandlight=" + "Bill" + "*doughnuts";  </script>  </head>  <body>  <h1>The cookie is set! </h1>  </body>  </html>

The name used for the cookie is sandlight=, and I can look for that name later when I read the cookie. The value set for the cookie follows the name assignment after the equals sign. The value is a string, combined of "Bill" and "*doughnuts". As you might have surmised, the combined value is really two values the name (Bill) and something that this person likes (doughnuts). However, the asterisk (*) needs some explaining. You cannot place spaces, commas, or semicolons in cookie values. Because the value is a string, you can put in multiple values by using a unique character to separate the different values and then use JavaScript to sort things out. Alternatively, you can use the escape( ) function to write data to a cookie and use unescape( ) to extract data from a cookie.

When designing a site that uses cookies to store information about viewers (such as customers or potential customers), JavaScript's capability to work with sub-strings comes in handy. By using substrings and delimiters, such as the asterisk (*), you can add a good number of values to a single cookie. However, your cookies need to stay within 4K for the name and value. So, while you can be creative in their use, still keep names and values relatively small. Many designers use numeric codes instead of descriptive strings. For example, in designing a site for an online bakery, I might have 200 different bakery items. Instead of coding the different items using names (such as bearclaws, muffins, and doughnuts), I could have values from 000 to 199, each representing a different item. When a cookie has been established, on the next visit, the customer would be presented with the items he had previously indicated as favorites by referencing the coded items.

Reading Cookies

Reading a cookie's value is a matter of loading and parsing the cookie. With a simple application, such as the one established for writing a cookie, the job is not too daunting. The parsing work can be done with a substring( ) function. The name, sandlight=, is 10 characters long (0 9), so the beginning of the value will be at 10. Hence, the statement to extract just the value would be this:

substring(10,cookie.length); 

For example, the following script will extract the contents of the cookie created with the script in the previous section:

<html>  <head>  <style>body {color:orangered; font-size:24pt} </style>  <script language="JavaScript">  var myCookies=document.cookie;  var cookieVal=myCookies.substring(10,myCookies.length);  document.write(cookieVal);  </script>  </head>  <body>  </body>  </html>

When you launch the script in your browser, you will see the following on your screen in a nice orange-red color in 24-point serif font:

graphics/doughnuts.gif

However, life with cookies is never quite so simple. In this next section, the discussion of optional attributes shows a bit more complexity in cookies.

Adding More Attributes

Cookies have the following four optional attributes:

  • expires Cookie expiration date

  • path Associated web pages

  • domain Setting for multiple domains

  • secure Boolean value for secure protocol

You can set some, all, or none of these attributes. Each attribute is placed in the order of this list, separated by semicolons. No labels identify the attributes, so you must remember the order and place dummy attributes if any are skipped.

Setting the Expiration Date

If expires is not set, your cookie is dropped at the end of the session; while it is optional, a cookie that evaporates at the end of the session where it is set is of little practical value. Therefore, most designers set the expiration date of cookies. Some cookies have relatively short expiration periods, but I have seen cookies set to expire in 20 30 years by optimistic designers.

Using JavaScript's built-in date objects, setting the expires attribute is quite simple. The date that goes into the actual cookie, though, must be in the Date.toGMTString( ) format. For example, the following would set an expiration date to the date specified:

var cookieGone=new Date("December 26, 2004");  document.cookie="sandlight=" + "TimeSample" + "; expires=" + cookieGone.  toGMTSring( ); 

Or, you can use a rougher setting, such as a couple of years:

var cookieGone=new Date( );  cookieGone.setFullYear(cookieGone.getFullYear( ) + 2);  var adios=cookieGone.toGMTString( );  document.cookie="sandlight=" + escape("Time Sample2") + "; expires=" + adios; 

The tricky part of setting the expiration is remembering that any label for the expiration date goes into quotes, along with the separating semicolon. In the two previous examples, look closely to how the expires= is encapsulated.

The Path

The best advice is to leave this setting alone. It automatically sets the path to the directory in which the page that generates the cookie resides. In cases where you want more than just those pages in the same directory to have access to a cookie, you can specify another path, such as /customers, and all pages within /customers will have access to the cookie. To open access to all web pages on the server, use / as the path. The format is as follows:

; path=/mypath 

The Domain

When you want to override the access to a cookie to more than the server on which it is created, you can use the domain attribute. By specifying a domain name, such as .sandlight.com, pages on any server in the .sandlight.com domain can access the cookie. The path setting for this wide range of cookie access would have to be set to /. The format is as follows:

; domain=.myDomain.xxx 

Note that a leading dot accompanies the domain name. Unless you write the entire URL beginning with http://, you need the leading dot.

Secure

If no secure setting is stated, the cookie is insecure. By typing the word secure, you make the cookie secure. The format is as follows, with no added values:

; secure 

Getting Information and Giving It Back

The trick in using cookies, of course, is to have the user provide information and be able to get that information for use in the web page. Whether the information is for a simple greeting whenever the viewer opens her page or is used to configure the page being presented to the user, existing information must be placed in the cookie. This next script is a relatively simple one that asks the viewer for information that is stored in a cookie upon the press of a button. Then, by pressing a second button, the viewer is presented with only the value stored in the name attribute, but not the name itself or the date expiration information. Therefore, pay close attention to the formatting used for configuring input and output. (Remember that &nbsp is simply an HTML nonbreaking space.)

<html>  <head>  <title>Read and Write Cookie</title>  <style type="text/css">        body {       background-color:rgb(200,198,159);        font-family:verdana;font-size:11pt }        #display {color:rgb(169,33,53); background-color:rgb(249,225,203) }  </style>  <script language="Javascript">  function yourCookie(name) {       var remain=new Date("November 9, 2005");        document.cookie= escape(name + document.baker.myCookie.value + "; expires=" +        remain.toGMTString( ) + ";");        }  function welcomeBack( ) {       var seeMe= unescape(document.cookie);        var tagIt=seeMe.indexOf(";");        seeMe=seeMe.substring(11,tagIt);        alert("Hello there, " + seeMe)        }  </script>  </head>  <body onLoad="document.baker.reset( )">  <div ID=display>&nbsp;  <form name="baker">        &nbsp;<Input type=text Name="myCookie" ><br>&nbsp;        Type in the value for your cookie and click the button to set the cookie<BR>        &nbsp;<input type=button value="Bake Cookie"        onclick="yourCookie('goodCookie=');"><p>&nbsp;        Click the button to read the value of the cookie along with a greeting. <br>        &nbsp;<input type=button value="See Cookie" onclick="welcomeBack( );"><br>        &nbsp;  </form>  &nbsp;</div>  </body>  </html>

The two functions provide a round-trip ticket for cookies. The first function sets the date and points the way to where the values can be found. This next line expects a name included when the function is placed in a tag to be launched:

function yourCookie(name) 

This line spells out where the information is to be found for the value (in the form) and sets up the expiration date:

document.cookie= escape(name + document.baker.myCookie.value + "; expires=" +  remain.toGMTString( ) + ";"); 

Because the value for name is coming from a form, you can expect user input for the contents of the cookie.

The second function reads the cookie's value only and then puts the substring into a variable that is presented in an alert() function (see Figure 13.3). These lines first pull all the data from the cookie in the initial line, using the unescape function to decode it:

Figure 13.3. Users will generally be entering the valu es for cookies, and that information can be used in future visits to the site.

graphics/13fig03.gif

var seeMe= unescape(document.cookie);  var tagIt=seeMe.indexOf(";");  seeMe=seeMe.substring(11,tagIt); 

Then, using the indexOf( ) method on the string containing the cookie, they locate the position of the semicolon that separates the value from the expiration date. Finally, the function looks for a substring beginning with the 12th character (remember, the string index begins with 0, not 1) because the name is 11 characters long. So, the substring between where the name (goodCookie=) ends and expires begins is the chunk of string where the value that you want can be found. (If you use a name other than goodCookie=, you will have to include the length of the name that you use as a starting point.)

Deleting Cookies

To delete a cookie, you need to provide it with an expiration date. It's quite simple because all you need to do is to set the same cookie name and then set an expiration date. The end user can always get rid of cookies set on her hard drive by throwing the cookie file into the Trash/Recycle Bin. A new cookie file is automatically regenerated when the browser is restarted.

Summary

Cookies can be used creatively to personalize a web site for visitors. The cookie information is not stored on a server, but rather on the user's hard drive; it represents the one thing that can be written to a user's disk from client-side scripts.

The designer's goal with cookies is to create a personalized environment for the user so that he will return to the site and keep using it. Cookies can be updated for changes in the site or the user's preferences. In the next several chapters, you will see how to store user information using server-side scripts and databases that are far more sophisticated and robust than cookies but that are used in a very similar way to cookies.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net