|
Week 14 THE PRODUCTShared Files Archive Final Plans Week 13 Animation LabDHTML Animation Week 12 DHTML Layers LabStretchtext Demo Week 11 DHTMLReplacement Lab Week 10 Progress ReportsStyle Sheets Style Sheets Lab Week 9 Maintaining StateCookies Invisible Forms State-Keeping Lab Week 8 Preloading ImagesJavaScript and Forms Assignment 3 Assignment 2 Work Prototype Logos Week 7 Barlow's DeclarationRandom Content Week 6 Name RevealedGround Rules 2 Revised Syllabus Week 5 Assignments for 10/7Week 4 Window Control DemoProposed Names Ground Rules Advice on Research Week 3 Group AssignmentsAssignment 1 Work Javascript, Buttons, Frames Assignment 2 Week 2 Lecture 9/9Platform Detection JavaScript Basics Week 1 Class ListWeek 1 Checklist JavaScript Content Assignment 1 Server Access Publication Research Topics Syllabus Requirements Course Concept |
Using JavaScript to Maintain StateI. Writing CookiesA cookie (short for "magic cookie") is a component of a fairly simple text file maintained on your computing device by your browser. The cookie file is much like the recording tape in an old-fashioned, pre-digital telephone answering machine: it contains a series of messages left by various people. Most of the messages in your cookie file, however, are not meant for human consumption. For a quick peek into your browser's cookie file, click the button below: One of the records you see here was made automatically when you loaded this page. In most cases, only a small part of the cookie file is exposed to the scripts on a page (usually, only cookies written from that page or another page in its directory; though there is a way around this limitation). Your actual cookie file probably contains a great deal of other material. Try opening it in a text editor for full disclosure. To see more complex cookie techniques in action, visit the demo page. We'll limit ourselves here to the most basic concepts: reading and writing cookie data. Writing a cookie is very simple. Every cookie consists minimally of a name/value pair. You can write a basic cookie from JavaScript with a statement like this: document.cookie = "myAttentionSpan=short;"; A few things need comment here. First, note that we don't have to specify a particular cookie file (there's only one per browser) or a location within that file; document.cookie simply means "add something to the cookie file." Also notice that there are two equals signs in the statement above. The first is the standard JavaScript assignment operator; the second, contained within the quotation marks and hence part of a string literal, separates the two halves of the name/value pair. Finally, observe the double semicolons, one within the string literal and the other outside. The inner semicolon is crucial: all cookie entries must end with a semicolon. The outer semicolon is the conventional end-of-statement marker and is not strictly required in JavaScript. In addition to the name/value pair, cookies may also have four additional attributes: an expiration date, a path, a domain, and a security setting. Here's an example of a cookie with all these extra toppings: document.cookie = "favoriteColor=puce; expires Sun, 24-Oct-10 12:00:00 GMT; path=/; domain=.ubalt.edu; secure;"; Note that all the settings are contained within the single set of double quotes. They are separated by semicolons. This cookie records the name/value pair "favoriteColor = puce" and specifies that this record will be automatically removed from the cookie file at midnight on the 24th of October, 2010. (Since the number of cookie records is finite and eventually new cookies displace the oldest entries, no cookie will ever really last this long.) The path setting indicates that this cookie is exposed to a script on any page located on its present Web server. If we wanted to limit this exposure to pages within the parent of the present directory, we'd give "/www/classes/" as the path value. The domain setting exposes the cookie to pages on any server within the specified domain. You would probably use it in place of a path setting. The "secure" setting requires that the cookie information be transmitted in encrypted form. If the word "secure" does not appear in a cookie, then the information is set without encryption. Never store passwords or other sensitive information in a non-secure cookie. These additional settings are optional--you may define a cookie with just a name/value pair. If not specified, the options default as follows: the cookie expires when the current browser session ends; path is limited to the present directory; no access is allowed to other servers in the domain; no encryption is used.
II. Reading CookiesRemember our earlier comparison of cookies to phone-machine messages? It might suggest one reason why reading cookies is considerably harder than writing them: it's necessary to scan through a linear stack of information until you find the entry you want. Fortunately, your computer does the scanning; but you have to tell it what to look for and how. Here's a relatively simple script for reading from the cookie file. It's almost identical to the script discussed in Ladd and O'Donnell, and to similar scripts in other books.
var result = null;
function getCookie(name)
{
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if(startOfCookie != -1)
{
startOfCookie += searchName.length;
var endOfCookie = myCookie.indexOf(";",startOfCookie);
result =
unescape(myCookie.substring(startOfCookie,
endOfCookie));
}
return result;
}
One note before we get into the details of the script: Ladd and O'Donnell include a statement at the beginning of the function setting the output variable result to null. This has caused problems in our experience, so we prefer to re-set result outside the function body; if getCookie() will be used more than once in your page, you'll need to re-set result each time it is invoked. The script begins by pulling the currently exposed contents of the cookie file into a variable called myCookie, preceded by a blank space and terminated by a semicolon. This formatting is necessary in case the current cookie is blank. Next we load a variable called searchName with the variable name, which was passed as a parameter, a blank space, and an equals sign. This matches the default formatting of the cookie file. Note that searchName corresponds only to the name part of the name/value pair. The indexOf method in the next line locates the first character position of the string searchName within the collection of exposed cookies. If the name we're looking for does not appear, the variable startOfCookie has the value -1. The declaration of endOfCookie is good form but seems not to be essential (the script still works after it is removed). The main part of the script is contained within the if condition that comes next. This condition ends execution early if the cookie name we've searched for is not found in the cookie file. Assuming it is found, we first assign a value to startOfCookie, increasing its (0) value to the length (maximum number of characters) of searchName. This lets us use the name part of the name/value pair but omit it from the output. The next line:
var endOfCookie =
myCookie.indexOf(";",startOfCookie);
loads into the variable endOfCookie a number that represents the first instance of the semicolon that occurs after the reference point in startOfCookie. The line following (which unfortunately gets rather mangled here) performs the crucial job of extraction:
result = unescape(myCookie.substring
(startOfCookie,endOfCookie));
What you see above is a single statement; the line break after "substring" is regrettable. This statement assigns to the output variable result the substring, or character subset of the cookie file, that runs from the position specified in startOfCookie to that specified in endOfCookie. The unescape() function is used in case the escape() function was originally used to encode the cookie--a standard procedure for dealing with problematic characters within the cookie value (e.g., semicolons). You can see this script in action on the demo page. III. Deleting CookiesThough cookies usually go away all by themselves in most people's experience, you may wish to delete a cookie deliberately. This is quite easy to do: simply write a new cookie with the name of the cookie you wish to delete, setting its expiration date to a value that predates the current moment. For example, consider this cookie: document.cookie = "favoriteColor=puce; expires Sun, 24-Oct-10 12:00:00 GMT;"; Here's one way to dispense with it: document.cookie = "favoriteColor=allGone; expires Wed, 20-Oct-99 12:00:00 GMT;"; The value "allGone" is purely arbitrary and in fact could have been omitted. The date chosen reflects the fact that this page was written in 2000. Note: whatever date you choose, be sure you get the day of the week correct--we had to check to be sure that October 20, 1999 fell on a Wednesday. It's easy to forget this detail, but neither writing nor deleting will work if you get the day wrong. Most authorities recommend you choose a date at least 3 days before the present, since time settings and browser quirks can cause problems otherwise. Ladd and O'Donnell discuss a method for automatically generating a date three days in the past (p. 546). Their method eliminates the day-of-the-week problem. |
||
|