« Wonders of keyword based advertising | Main | "Effective Java" or "Heads First Java" »

Found a bug in JavaScript Cookie class of JavaScript: The Definitive Guide

Hoping to save some time, I decided to use the JavaScript Cookie class provided in the otherwise excellent book JavaScript: The Definitive Guide, 5th Edition. However, my program was not working as intended -- the cookies that were supposed to last the whole session were getting reset at every new page. After an hour of alert() and FireBug assisted debugging finally helped me to track down the problem: the Cookie class was not behaving properly. Just submitted an errata to O'reilly's. Here is the submission:
document.cookie value on FireFox includes a blank space after ';'. As a result, the code to extract a particular cookie value doesn't work:
    var cookies = allcookies.split(';');
    var cookie = null;
    for(var i = 0; i < cookies.length; i++) {
        // Does this cookie string begin with the name we want?
        if (cookies[i].substring(0, name.length+1) == (name + "=")) {
            cookie = cookies[i];
            break;
        }
    }
This can be easily fixed by first replacing all blanks with zero length strings, as in:
    var cookies = allcookies.replace(" ", "").split(';');
My program is happy now.
Visit Charteous, my Web 2.0 hobby project.

Comments (1)

Jason:

what happens if you have a space in the cookie value?

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on January 12, 2007 6:16 AM.

The previous post in this blog was Wonders of keyword based advertising.

The next post in this blog is "Effective Java" or "Heads First Java".

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33