A Simple Cookie Object

JavaScript has recently added new storage mechanisms for holding data on the local computer or in the browser so cookies are not quite as necessary for this activity as they used to be. There are occasions though where you might want to share the stored data with the server and in this instance cookies are the only mechanism that allows for such sharing and also for retaining information between browser sessions.

We can make all of our cookie processing much simpler if we create our own cookie object with read, write and delete methods that work closer to the way you'd expect these to work than directly referencing the document.cookie object.

As well as being able to write session or first party cookies (retained between browser sessions) we can also restrict the cookie to a specific sub-domain of folder. The write method caters for this by allowing between two and four parameters. The first parameter is the cookie name, the second is the value that cookie is to have. If a third parameter is specified then it is the number of days that the cookie will be retained, if this parameter is omitted then a session cookie will be created. The optional fourth parameter if it starts with a / identifies the folder that the cookie is restricted to, otherwise it identifies the domain the cookie is restricted to. To ensure that cookies written by a page can be read back by the same page without the page being reloaded (something not normally possible with cookies) the cookie is also saved as a property of the cookie object.

With this particular cookie object the read method simply specifies the name of the cookie you want to read and if it exists it returns the value of that cookie and if it doesn't exist it returns null. The read method first checks if the cookie has been saved as a property of the cookie object before looking at the cookies read in by the page in order to pick up the latest value for the cookie it the cookie has already been (re)written by this page.

The delete method simply calls the write method with a date in the past and then deletes the associated property from the cookie object.


Examples of how you can reference your cookies via this object include:

mycookie = cookie.read('oneweekcookie');


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow