So I was working last night on finishing a prototype PHP library for genetify. Everything was going great (it is amazing how fast you can re-write code, even in another language), until it came time to manipulate cookies client-side in Javascript that were set server-side in PHP. The cookie data was being read and passed on successfully to the rest of the system so my confidence in the PHP code was high. But when it came time to rewrite parts of the cookie data client-side -- the last test I wanted to try before calling it a night -- I ran into problems. Overwriting the server side cookie appeared to create a whole new cookie with the same name. Until this experience, I had always understood cookies to exists as keyed values in a namespace, altho represented by document.cookie as a string. So I tried to discover some sort of configuration of HTTP requests and client and server state that could reconcile the two cookies. As the night wore on, I spiraled down into a kind of mental labyrinth until I had the sense to give up.
Today, with a fresh start, I systematically tested my assumptions about cookies and I discovered after half an hour that Firefox's document.cookie prefixes the domain info in the cookie with a period "." , which apparently puts the cookie in a different namespace for writing (altho not reading!). It is no surprise that I missed it the night before. Can you spot the odd man out?
mydomain.com, mydomain.com, mydomain.com, .mydomain.com, mydomain.com
Not normally judgmental, I humbly name document.cookie a TERRIBLE API. Even before this epsiode, from my earliest days making websites, I hated it. Let's count all the sins:
1. Document.cookie is represented as a string, but the equals sign "=" appends to it. Why not "+=" ?
2. You can write to document.cookie with extra params (expires, domain, path) but these are not accessible anywhere in the DOM. Come on!
3. You can only delete a cookie by giving it an expiry in the past. Why not an empty string or null value?
4. The namespace problem described above. How to identify two cookies with the same name but different domains or paths?
5. All these problems could be avoided by making document.cookie a *normal* javascript-DOM object. Then every bloody javascript framework out there wouldn't need the functions setCookie and getCookie.
Friday, October 5, 2007
Subscribe to:
Post Comments (Atom)
1 comment:
Wow, my longest and probably most boring post... nothing like a traumatic coding experience to get me talking.
Post a Comment