A while ago I mentioned that my school gives students and faculty Novel NetDrive accounts. This means we can all publish simple websites on their service, but get no server side scripting. This makes that space great for teaching students HTML but relatively useless for everything else.
I probably don’t need to tell you that the example above is a very, very bad coding practice. You really don’t want to eval any code that might have been tampered with. Since we are storing our object in a cookie which can then be modified on the client machine, we are really opening ourselves for abuse. So while storing functions inside cookies is possible, I would not recommend it.
What you want to do is to serialize your objects into JSON, and the safely parse it back while making sure you are actually getting back JSON object rather than random code. There is a really good plugin that does this for you. So your code will look something like this:
The secureEvalJSON method is much safer than just running eval on arbitrary code. The pluging also has an “unsafe” eval version, but I would not recommend using it unless you can guarantee the cookies haven’t been tampered with (and in most cases you can’t).
There is a small caveat you need to keep in mind. The space you have to work in is very limited. Fore example, IE only allows you to store around 4KB of data per domain. This is not per cookie, but a total space you have for all your name-value cookie pairs. This means that sticking a huge JSON object (or many smaller ones) into a cookie just won’t work. IE will silently drop cookies that exceed this limit. So use this technique sparingly, and if you can, compress the data as tightly as possible.