Cookies are small pieces of information stored by a user's browser on his or her machine. Although they are supported in most modern browsers, cookies are quite limited compared to the default behaviors described earlier. They cannot exceed 4 kilobytes in size, and some characters are restricted.
A cookie is accessed through the cookie property of the document object. Information typically is stored in a cookie in name=value pairs. Several other types of information can be used in cookies as well, including domain, path, and security settings and an expiration date for the cookie. The following line of script demonstrates storing a variable and an expiration date in a cookie:
document.cookie= "myGreeting=Hi; expires=Mon, 31 Dec 1999 23:59:59 UTC;" |
The variable of name myGreeting is given the value of Hi. The cookie is set to expire at the end of 1999. If no value is set for expires, or if the expiration date is set to a time in the past, the cookie will be deleted as soon as the browser is closed. Code Listing 22-6 and Figure 22-6 demonstrate a more sophisticated use of cookies, including both storing and retrieving information from a cookie and displaying all names and values in a cookie.
Code Listing 22-6.
|
Figure 22-6. This page saves and retrieves information in cookies. This screen shows what happens when the Display button is clicked after two new cookies have been created.
The user can create a cookie by typing a name in the New Cookie Name field and a value in the New Cookie Value field and clicking Create. These steps run the setCookie function, which takes a name and value and commits them to the cookie. The user can retrieve a particular name=value pair from the cookie by typing the cookie name in the Name field and clicking Show. This step runs the getCookie function, which splits the cookie up into its separate name=value pairs and compares each name to the value of the Name field. When it finds one that matches, it returns the value of that name=value pair. The entire contents of the cookie can be displayed by clicking the Display button. The file cookies.js in the tools folder on the companion CD includes more sophisticated tools for cookie manipulation that can be easily added to any Web page.