Click here to Skip to main content
Click here to Skip to main content

Web site persistence made easy.

By , 2 May 2002
Rate this:
Please Sign up or sign in to vote.

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:

  1. SSL required
  2. Domain
  3. 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
<!-- Include the cookie object into your HTML -->
<script language="javascript" src="cookie.js"></script>

<!-- Construct and Initialize cookie object for use in your project -->

<script language="javascript">
  //Instantiate cookie class
  var myCookie = new Cookie();

  //Cookies didn't exist, create new cookies
  if(!myCookie.Load()){
    myCookie.Create("User", 10); //Create cookie that expires in 10 days
    myCookie.Create("Pass", 15);

    //Add sub-item(s) to named cookie(s)
    myCookie.AddItem("User", "Gretzky");
    myCookie.AddItem("User", "Lemieux");
    myCookie.AddItem("User", "Sakic");
    myCookie.AddItem("User", "Pronger");

    myCookie.AddItem("Pass", "Hockey");

    //Store cookies
    myCookie.Save();
  }
  else{ //Cookies were available so ignore 
        //creating new ones and just load previous
        //This is web site persistence at it's best
    //alert(document.cookie);

    //Debug dump of all cookie items
    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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

alex.barylski
Web Developer
Canada Canada
No Biography provided

Comments and Discussions

 
QuestionJScript or Javascript? PinmemberNish [BusterBoy]12-Apr-02 17:48 
AnswerRe: JScript or Javascript? PinmemberShog912-Apr-02 18:01 
GeneralRe: JScript or Javascript? PinmemberPhilip Patrick13-Apr-02 0:53 
AnswerRe: JScript or Javascript? PinmemberHockeyDude12-Apr-02 18:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140421.2 | Last Updated 3 May 2002
Article Copyright 2002 by alex.barylski
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid