16.2. Storing Cookies
document.cookie = "version=" + escape(document.lastModified);
A cookie written as described above lasts for the current web-browsing session but is lost when the user exits the browser. To create a cookie that can last across browser sessions, include an expiration date by setting the expires attribute. You can do this by setting the cookie property to a string of the form:
When setting an expiration date like this, date should be a date specification in the format written by Date.toGMTString( ). For example, to create a cookie that persists for a year, you can use code like this:
var nextyear = new Date( ); nextyear.setFullYear(nextyear.getFullYear( ) + 1); document.cookie = "version=" + document.lastModified + "; expires=" + nextyear.toGMTString( );
; path=path ; domain=domain ; secure
To change the value of a cookie, set its value again, using the same name and the new value. Use whatever values are appropriate for expires, path, and the other attributes. 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 delete expired cookies immediately, so a cookie may remain in the browser's cookie file past its expiration date.
16.2.1. Cookie Limitations
Cookies are intended for infrequent storage of small amounts of data. They are not intended as a general-purpose communication or data-transfer mechanism, so you should use them in moderation. Web browsers are not required to retain more than 300 cookies total, 20 cookies per web server (for the entire server, not just for your page or site on the server), or 4 kilobytes of data per cookie (both name and value count toward this 4-kilobyte limit). The most restrictive of these is the 20 cookies per server limit. In order to avoid reaching that limit, you may want to avoid using a separate cookie for each state variable you want to save. Instead, you can encode several related state variables into a single named cookie. Example 16-1, later in this chapter, shows one way that this can be done.
Copyright © 2003 O'Reilly & Associates. All rights reserved.