Skip to Main Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced content levelIntermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Storing Cookies

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

               name=value

For example:

document.cookie = "version=" + escape(document.lastModified);

The next time you read the cookie property, the name/value pair you stored is included in the list of cookies for the document. Cookie values 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. If you do this, you’ll have to use the corresponding unescape( ) function when you read the cookie value.

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:

               name=value; expires=date

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(  );

Similarly, you can set the path, domain, and secure attributes of a cookie by appending strings of the following format to ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
Coding with JavaScript For Dummies

Coding with JavaScript For Dummies

Chris Minnick, Eva Holland

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata