Javascript: The Definitive Guide

Previous Chapter 15 Next
 

15.3 Storing Cookies

To associate a temporary cookie value with the current document, simply set the cookie property to a string of the form:

name=value
The next time you read the cookie property, the name/value pair you stored will be included in the list of cookies for the document. As noted above, the cookie value may not include semicolons, commas or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie.

A cookie written as described above will last for the current web browsing session, but will be lost when the user exits the browser. To create a cookie that can last across browser sessions, include an expiration date. You can do this by setting the cookie property to a string of the form:

name=value; expires=date
When setting an expiration date like this, date should be a date specification in the format written by Date.toGMTString().

Similarly, you can set the path, domain, and secure fields of a cookie by appending strings of the following form to the cookie value before that value is written to the document.cookie property:

; path=path
; domain=domain
; secure

To change the value of a cookie, set its value again, using the same name (and the same path and domain, if any) and the new value. To delete a cookie, set it again using the same name, an arbitrary value, and an expiration date that has already passed. Note that the browser is not required to immediately delete expired cookies. In practice, with Netscape, cookie deletion seems to work more effectively if the expiration date is in the relatively distant (several hours or more) past.


Previous Home Next
Reading Cookies Book Index Cookie Limitations