Javascript: The Definitive Guide

Previous Chapter 15 Next
 

15.2 Reading Cookies

When you use the cookie property in a JavaScript expression, the value it returns is a string containing all the cookies that apply to the current document. The string is a list of name=value pairs separated by semicolons, where name is the name of a cookie, and value is its string value. You can use the String.indexOf() and String.substring() methods to determine the value of the named cookie you are interested in. Or, you may find it easier to use String.split() to break the string into individual cookies.

Once you have obtained the value of a cookie in this way, you must interpret that value based on whatever format or encoding was used by the creator of that cookie. For example, the cookie might store multiple pieces of information in colon-separated fields. In this case, you would have to use appropriate string methods to extract the various fields of information.

The value of a cookie must not contain any semicolons, commas, or whitespace. Because these are commonly used characters, it is common to use the JavaScript escape() function to encode cookie values before storing them, and the unescape() function to decode the values after retrieving them.

Note that the Document.cookie property provides no way to obtain the domain, path, expiration, or secure fields associated with a cookie.


Previous Home Next
An Overview of Cookies Book Index Storing Cookies