Thursday, July 23, 2009

Javascript Cookies

Thanks to Jason McCreary, I was able to get Javascript cookies working very easily.

The one thing missing on that page, though, is a more general bit of help with how to safely use cookies. My first attempt (below) almost worked perfectly, however there was a little bit of weirdness.


Cookie.init({name: "macBlogMenu"});
open_nodes = Cookie.getData("open_nodes");
<do stuff>
Cookie.setData("open_nodes",open_nodes);


I am working on a rails site which is defined such that /blog shows the current blog and /blog/N shows the blog with id=N. Since both of these show a blog entry and the cookie was to keep track of menu state on the blog display page, I used a javascript cookie with just default options. This was a bad idea. State was not being updated when I looked at other blog entries, only when I used the default (current) blog entry.

Anyone familiar with cookies would probably already know the answer is to define the path option for the Cookie object. So the better code is:


Cookie.init({name: "macBlogMenu"});
Cookie.options.path = "/blog/";
open_nodes = Cookie.getData("open_nodes");
<do stuff>
Cookie.setData("open_nodes",open_nodes);


The path needs to be "/blog/" because of the scope rules for cookies. Documents at root (one level - i.e. /blog), can read and change cookies for documents on lower nodes. Lower nodes (/blog/3) can read cookies defined for higher level paths, but not set them. By defining the path this way, it is accessible to /blog and /blog/N documents.

No comments:

Post a Comment