YUI cookies

Every time I talked about web cookies, my ex-girlfriend would say, “Mmmm, cookies.”

Besides messing with my train of thought, it also gave me an unhealthy obsession with cookie implementations in web development. Today, I was taking apart how YUI implements subcookies, and the source had this comment in the subcookie parser…

JavaScript:
  1. /**
  2. * Parses a cookie hash string into an object.
  3. * @param {String} text The cookie hash string to parse. The string should already be URL-decoded.
  4. *…
  5. */

O RLY? Because it’s “already” URL-decoded, I don’t have to worry about double-encoding/decoding? That’s news to me.

Time to test the front-end coding wizardry:

JavaScript:
  1. // Include YUI utilities, logger, and cookie-beta (2.5.0)
  2. // logger
  3. var myLogReader = new YAHOO.widget.LogReader(document.body.appendChild(document.createElement("div"));
  4.  
  5. var Cookie = YAHOO.util.Cookie;
  6. //Cookie.set("example", '');
  7. var ex_cookie = Cookie.get("example");
  8. var foo = Cookie.getSub("example", "foo");
  9. var bar = Cookie.getSub("example", "bar");
  10. var bogus = Cookie.getSub("example", "and");
  11.  
  12. YAHOO.log("The value of cookie 'example' is: " + ex_cookie);
  13. YAHOO.log("The subcookie 'foo' is: " + foo);
  14. YAHOO.log("The subcookie 'bar' is: " + bar);
  15. YAHOO.log("The subcookie 'and' is: " + bogus);
  16.                        
  17. //set subcookie values
  18. Cookie.setSub("example", "foo", "Can YUI handle &and='s or not?");
  19. Cookie.setSub("example", "bar", "more data");

The output after the second reload is:

The value of cookie 'example' is: foo=Can YUI handle &and='s or not?&bar=more data
The subcookie 'foo' is: Can YUI handle
The subcookie 'bar' is: more data
The subcookie 'and' is: 's or not?

Subcookie “and”? Doh! I guess that’s why this code is listed as “beta.”

Cookie Monster
Cookie Monster doesn’t like broken subcookies!

Here is a hint: If you nest serializations, you need to nest your escaping/unescaping.

(On the other hand, you only need to escape "=" and "&" instead of using this strategy.)

3 Responses to “YUI cookies”

  1. Russell Davis Says:

    Oh the irony. The tooltip on the final highlighted phrase is broken due to an unescaped quote character.

  2. Nicholas C. Zakas Says:

    Thanks for the heads up. You’ll be happy to know that YUI 2.5.1, released today, fixes this issue.

  3. tychay Says:

    @Russell. Nice catch. I missed it myself. :-)
    @Nicholas: That’s great to hear. We upgraded on Thursday.

Leave a Reply