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 ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.