home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

16.3. Reading Cookies

When you use the cookie property in a JavaScript expression, the value it returns is a string that contains all the cookies that apply to the current document.[53] 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. This value does not include any of the attributes that may have been set for the cookie. To determine the value of a particular named cookie, you can use the String.indexOf( ) and String.substring( ) methods, or you can use String.split( ) to break the string into individual cookies.

[53]In Internet Explorer 3, the cookie property works only for Document objects that were retrieved using the HTTP protocol. Documents retrieved from the local filesystem or via other protocols, such as FTP, cannot have cookies associated with them.

Once you have extracted the value of a cookie from the cookie property, you must interpret that value based on whatever format or encoding was used by the cookie's creator. 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. Don't forget to use the unescape( ) function on the cookie value if it was encoded using the escape( ) function.

The following code shows how you might read the cookie property, extract a single cookie from it, and use the value of that cookie:

// Read the cookie property. This returns all cookies for this document.
var allcookies = document.cookie;
// Look for the start of the cookie named "version"
var pos = allcookies.indexOf("version=");

// If we find a cookie by that name, extract and use its value
if (pos != -1) {
    var start = pos + 8;                       // Start of cookie value
    var end = allcookies.indexOf(";", start);  // End of cookie value
    if (end == -1) end = allcookies.length;
    var value = allcookies.substring(start, end);  // Extract the value
    value = unescape(value);                       // Decode it

    // Now that we have the cookie value, we can use it.
    // In this case, the cookie was previously set to the modification
    // date of the document, so we can use it to see if the document has
    // changed since the user last visited.
    if (value != document.lastModified)
        alert("This document has changed since you were last here");

Note that the string returned when you read the value of the cookie property does not contain any information about the various cookie attributes. The cookie property allows you to set those attributes, but it does not allow you to read them.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.