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.”
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.)
Oh the irony. The tooltip on the final highlighted phrase is broken due to an unescaped quote character.
Thanks for the heads up. You’ll be happy to know that YUI 2.5.1, released today, fixes this issue.
@Russell. Nice catch. I missed it myself. 🙂
@Nicholas: That’s great to hear. We upgraded on Thursday.