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

JavaScript: The Definitive Guide, Fourth Edition

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

Cookie Example

Example 16-1 brings together all the aspects of cookies we have discussed so far. First, the example defines a Cookie class. When you create a Cookie object, you specify a Document object, a name for the cookie, and, optionally, an expiration time, a path, a domain, and a boolean value that indicates whether the cookie should be secure. After creating a Cookie object, you can set arbitrary string properties on this object; the values of these properties are the values stored in the cookie.

The Cookie class defines three methods. The store( ) method loops through all of the user-defined properties of the Cookie object and concatenates their names and values into a single string that serves as the value of the cookie. The load( ) method of a Cookie object reads the cookie property of the Document object to obtain the values of all the cookies for the document. It searches this string to find the value of the named cookie and then parses this value into individual names and values, which it stores as properties of the Cookie object. Finally, the remove( ) method of the Cookie object deletes the specified cookie from the document.

After defining the Cookie class, Example 16-1 demonstrates a useful and elegant way to use cookies. The code is somewhat complicated but is worth studying carefully. You may want to start with the test program at the end of the example; it shows a typical usage of the Cookie class.

Example 16-1. A utility class for working with cookies ...

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
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata