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