Section 19.3. Reading Cookies


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

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 decodeURIComponent( ) function on the cookie value if it was encoded using the encodeURIComponent( ) function.

The following code shows how to 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 = decodeURIComponent(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.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net