Reading Out Cookies


var cookies = document.cookie.split(/; /g); 


When accessing document.cookie, JavaScript retrieves a list of all cookies the browser would send to the current server. Unfortunately, this access is not available in the form of an array, but of a string. For instance, the previous phrase would generate the following value for document.cookie:

myLanguage=JavaScript; myOtherLanguage=PHP:%20Hypertext%20Preprocessor 


Therefore, to get cookies out of this value, the following steps must be taken:

1.

Split the cookie string at "; " (to get individual cookies).

2.

Identify the first equal sign (=) in every cookie as the name/value delimiter.

Since the cookie values may contain equal signs as well, the first occurrence of an equal sign must be used. The following code prints out all cookies in the form of an HTML table. Before it's written to the page, HTML special characters are properly escaped with an HtmlEscape() function.

Reading Out Cookies (getcookies.html; excerpt)

<script language="JavaScript"   type="text/javascript"> document.write("<table><tr><th>Name</th><th>Value</th></tr>"); var cookies = document.cookie.split(/; /g); for (var i=0; i<cookies.length; i++) {   var cookie = cookies[i];   if (cookie.indexOf("=") == -1) {     continue;   }   var name =     cookie.substring(0, cookie.indexOf("="));   var value =     cookie.substring(cookie.indexOf("=") + 1);   document.write("<tr><td>" +                  HtmlEscape(name) +                  "</td><td>" +                  HtmlEscape(unescape(value)) +                  "</td></tr>"); } document.write("</table>"); </script> 

Figure 7.2 shows the possible output of the preceding listing.

Figure 7.2. All cookies in the system are printed in the browser.


When the value of one specific cookie is required, a helper function may come in handy. It looks for the given cookie name and returns the value (which is everything to the right of the cookie name, until the next semicolon or the end of the string):

Reading Out a Single Cookie (getsinglecookie.html)

function getCookie(name) {   var pos = document.cookie.indexOf(name + "=");   if (pos == -1) {     return null;   } else {     var pos2 = document.cookie.indexOf(";", pos);     if (pos2 == -1) {       return unescape(         document.cookie.substring(           pos + name.length + 1));     } else {       return unescape(         document.cookie.substring(           pos + name.length + 1, pos2));     }   } } 

Tip

Never forget to unescape the cookie value data. In the given example, this was done by using unescape() because the original cookies were escaped using escape(). If you are using another escaping scheme, you have to use the proper unescaping mechanism in your code.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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