Samstag, Dezember 05, 2009

How to read cookie values in JavaScript

I recently had some odd effects with some pages that use cookies to store some local information. The bug seems to be widely spread in many web applications so here are my findings:

To read the value of a specific cookie that was set previously you have to analyze the string in document.cookie that contains all cookies. It’s a very readable format and looks like:

a=a101; aha=aha101; bob=bob101; b=b101; c01=c0101

The trick is to find the right cookie in this string and extract the value.

I used a JavaScript function, named getCookie() that searched for the position of the cookie name by using

start = document.cookie.indexOf(name + "=");

… and this is wrong in some cases.

If you search for the cookie named "b" in the sample above you will get a starting-position within the cookie named "bob" because the indexOf function stops at the first occurrence of the text "b=".

This seems to be a very common approach and some educational web sites still publish this kind of code that contains the mistake.

It’s easy to fix this line by including the space character:

var start = document.cookie.indexOf(" " + name + "=");
if (start >= 0) {
  start += 1
} else if (document.cookie.indexOf(name + "=") == 0) {
  start = 0;
} // if

But there is a more elegant solution when using regular expressions and even the retrieval of the value gets easier that I found at

Here is the full function:

function get_cookie (cookie_name)
  var results = document.cookie.match('(^;) ?' + cookie_name + '=([^;]*)(;$)');
  if (results)
    return (unescape(results[2]));
    return (null);

Check your code.

Keine Kommentare: