Introduction
Your browser uses the HTTP protocol when viewing web sites and unfortunately cannot keep state between sessions and a web site refresh. As the Internet evolved, browser authors realized this was a shortcoming and later introduced cookies to enable web site persistence. Browsers solve this problem by allowing tiny amounts of data to be serialized from a small database/textfile(s) that your browser keeps track of. Cookies are analogous to the Windows registry, in that, you as the programmer never has to worry about cookie location, the browser takes care of this for you. Normally you access/modify the cookie data using the document.cookie
property, which both IE and NS browsers support (6th generation browsers anyway). However cookie data is very unstructured and requires substantial parsing and decoding in order to make any sense. Cookies are stored internally as one long string; this is the cookie format used by most browsers (if not all).
All are optional with the exception of the name=value pair.
name=value;
expires=date;
domain=domainname
path=pathname;
secure;
This is what a cookie might look like:
User=HockeyDude; expires=Thu,01-Jan-70 00:00:01 GMT;
domain=www.mydomain.com; path=/images; secure;
Pass=Gretzky; expires=Thu,01-Jan-70 00:00:01 GMT;
domain=www.mydomain.com; path=/images; secure;
The above demonstrates the storage of ONLY 2 cookies, what about email or other information? Traditionally you would have to parse/split the entire cookie string until you had what you wanted in individual variables or elements in an array. Repeating this process every time you build a web site is kind of redundant and would only waste time and money. Many JScript authors have written utility functions that are generic enough to use on any site and save you hours of programming. As good as these functions are, many don't implement them in an OOD friendly way and they don't easily allow more than one item to be stored per cookie.
About
The JScript object I have designed has the following advantages over many existing cookie helper functions.
- Object Oriented Design or as much as JScript will allow (i.e.: no public/private methods)
- Easily add/remove sub-items from named cookies to take advantage of cookie space. This is important because many browsers impose a limit on the number of cookies you can store.
- Allow easy change of expiry date via mutator functions. Normally this would involve having the programmer copy the cookie, erase the cookie, change the date and then write the cookie.
- Cookies and sub-items are stored in an array when using this object, which allows you to quickly and efficiently change the cookie(s) as required, instead of parsing, reading, writing, parsing, etc...
Of course nothing is perfect, so for the sake of brevity, I have excluded the optional parameters used in cookies. These are:
- SSL required
- Domain
- Pathname
For the most part, these are rarely needed, so you won't be missing much. However if you find you do need them, the script can be quickly changed. I will upon request, implement this feature (enough requests anyway).
How to use the object
The usage of the cookie
object is incredibly easy and much more object friendly than most comparative classes. The following are the public methods available to you.
[] brackets are optional parameters
//Construction
Cookie([deliminator character - default is period]) - Constructor
//Initialization
GetCookieCount() - returns the number named cookies
Fetch(index) - Returns the cookie name at the given index
Create(name, days) - Create a named cookie
and the number of days before expiry
Modify(name, days) - Modifies the days before
expiry of an existing named cookie
Delete(name) - Removes the named cookie
and all it's sub-items from cookie database
GetCount(name) - Returns the number of sub-items under a named cookie
AddItem(name, value) - Adds a sub-item to a named cookie
GetItem(name, index) - Returns the
sub-item of a named cookie at a given index
DelItem(name, index) - Removes the
sub-item of a named cookie at a given index
//Serialization
Load() - Loads cookie data from the browser database
Save() - Saves cookie data from internal
array to browser database for persistence
<!--
<script language="javascript" src="cookie.js"></script>
<!--
<script language="javascript">
var myCookie = new Cookie();
if(!myCookie.Load()){
myCookie.Create("User", 10);
myCookie.Create("Pass", 15);
myCookie.AddItem("User", "Gretzky");
myCookie.AddItem("User", "Lemieux");
myCookie.AddItem("User", "Sakic");
myCookie.AddItem("User", "Pronger");
myCookie.AddItem("Pass", "Hockey");
myCookie.Save();
}
else{
for(i=0; i<myCookie.GetCookieCount(); i++)
{
for(j=0; j<myCookie.GetCount(myCookie.Fetch(i)); j++)
alert(myCookie.Fetch(i) + "=" +
myCookie.GetItem(myCookie.Fetch(i),j));
}
}
</script>
Cookies don't only have to be used for client-side persistence, but can also be useful in communicating to scripts running on the server. For instance I think CodeProject uses cookies in this fashion. When you first log on, you'll notice in the top-left corner, Chris asks you for your password and email, but after you log on once, you'll never get asked again (until cookies expire). This is the magic of cookies at work. Your email and password are stored on your machine and whenever the CodeProject ASP scripts run, I assume they read your cookies and log you in automatically, thus saving you from having to log in manually (very nice feature). This cookie
class is pretty flexible and can be used for multiple applications, including shopping carts, user log-in, storing the position of floating division, you name it. It's all up to your imagination from here on in.
Short-comings
- You cannot specify different cookie paths or domains
- You cannot choose whether you want secure cookies
- It appears to not work properly when used with ASP...?
In either case, I have found that most of the time these are not required and for the sake of simplicity I have ignored these options.
Bugs
When removing the sub-items from named cookies, you can never remove the last cookie (index one) 100% for some reason (which I've yet to find and if you do, and know how to fix it, let me know please). The element will be blanked, but it is still saved to cookie file alongside with the deliminator.
So the original (internal object) cookie:
652525254424.HockeyDude.Dillweed
When there are no more elements to remove will look like this:
652525254424._____
So please if you have some spare time, glance through and try and find the bug and correct it, I'll make sure I mention you in the credits. I have already started working on another object, so I haven't the time to do this myself.
I'm not promising 100% technical accuracy, so please inform me of mistakes. Thank you!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.