Compact Cookie Unit
by
, 06-24-2009 at 12:50 AM (77841 Views)
Cookies are often confusing. Much of the confusion can be eliminated if you know that all cookies are strings. If you want to store an array, function, number, or an object in a cookie, you must convert it to a string before storage and upon retrieval change it back into the object/array/function/number that it was. Cookies are therefore best used for string storage and retrieval. This unit doesn't pretend to eliminate all of the possible confusions that can arise from "when and where in my code is the best place to set/read/delete the cookie". However, it does greatly simplify those actions:
Usage is indicated in the comments. For example, to set a cookie named 'bob' to a value of 'your uncle' to persist for 2 days:Code:var cook = { set: function(n, v, d){ // cook.set takes (name, value, optional_persist_days) - defaults to session if no days specified if(d){var dt = new Date(); dt.setDate(dt.getDate() + d); d = '; expires=' + dt.toGMTString();} document.cookie = n + '=' + escape(v) + (d || '') + '; path=/'; }, get: function(n){ // cook.get takes (name) var c = document.cookie.match('(^|;)\x20*' + n + '=([^;]*)'); return c? unescape(c[2]) : null; }, kill: function(n){ // cook.kill takes (name) cook.set(n, '', -1); }, killall: function(){ // cook.killall takes no parameters var cookies = document.cookie.split(';'), i = cookies.length - 1; for (i; i > -1; --i){ cook.kill(cookies[i].split('=')[0]); } } };
To read said cookie (it will return its string value if set, null if not set) - no semicolon follows the example because it will most often be a part of an if or variable assignment statement.Code:cook.set('bob', 'your uncle', 2);
To wit:Code:cook.get('bob')
To erase said cookie:Code:if(cook.get('bob')
) do one thing else do another thing
That's it!Code:cook.kill('bob');
Edit: July 2010 - changed the name of the object to cook from cookie as this was giving errors in some browsers. Added killall function.