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…

/**
 * Parses a cookie hash string into an object.
 * @param {String} text The cookie hash string to parse. The string should already be URL-decoded.
 *…
*/

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:

// Include YUI utilities, logger, and cookie-beta (2.5.0)
// logger
var myLogReader = new YAHOO.widget.LogReader(document.body.appendChild(document.createElement("div"));

var Cookie = YAHOO.util.Cookie;
//Cookie.set("example", '');
var ex_cookie = Cookie.get("example");
var foo = Cookie.getSub("example", "foo");
var bar = Cookie.getSub("example", "bar");
var bogus = Cookie.getSub("example", "and");

YAHOO.log("The value of cookie 'example' is: " + ex_cookie);
YAHOO.log("The subcookie 'foo' is: " + foo);
YAHOO.log("The subcookie 'bar' is: " + bar);
YAHOO.log("The subcookie 'and' is: " + bogus);

//set subcookie values
Cookie.setSub("example", "foo", "Can YUI handle &and='s or not?");
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.)

Published by

tychay

light writing, word loving, ❤ coding

4 thoughts on “YUI cookies”

Leave a Reply

Your email address will not be published. Required fields are marked *