Matt Snider JavaScript Resource

Understanding JavaScript and Frameworks

Wednesday, June 6, 2007

Cookies

Cookie Monster

Well, unfortunately, not the kind you can eat (sorry, cookie monster). I was explaining cookies to someone in a forum today and thought I would share my thoughts.

Cookies are a good way to store temporary information about a user on their computer as long as they have them enabled. Fortunately, most people who have JavaScript enabled also have cookies enabled, so we will not worry about accessibility too much. Cookies have the advantage of being stored client-side in the user’s temporary internet files, so they are computationally cheap to set and retrieve. However, you should never store any private data in cookies or use them to access any private systems, as cookies are hackable and easy to forge. That said, many login systems rely on cookies to store a temporary session key; cookies are a well established technology and can be powerful if used right.

I often use cookies with tabs or toggles so that when a user switches pages and returns to the page with my widget the last state is remembered (this will be discussed at some point in the future). For the sake of today’s article, here are three simple function that I use as part of my Core package.

var createCookie = function(name, value, days) {
	var expires=null;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else {expires = "";}
	document.cookie = name+"="+value+expires+"; path=/";
};
//
var eraseCookie = function(name) {
	Core.getClient().createCookie(name, '', -1);
};
//
var readCookie = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') {c = c.substring(1,c.length);}
		if (c.indexOf(nameEQ) == 0) {return c.substring(nameEQ.length, c.length);}
	}
	return null;
};

I do not remember where I originally found them from, so I cannot take credit, but I have used these functions for a long time.

posted by Matt Snider at 10:44 pm  

3 Comments »

  1. http://www.youtube.com/watch?v=BovQyphS8kA

    Comment by Atish — June 14, 2007 @ 11:35 am

  2. sweetness, thanks atish. ^_^

    Comment by admin — June 14, 2007 @ 1:55 pm

  3. […] Cookie Management Function […]

    Pingback by Introducing Core JavaScript File and Namespace | JavaScript Weblog — June 15, 2007 @ 9:00 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress