SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

JavaScript cookies library

Posted on June 2nd, 2007 by Alex Gorbatchev. In JavaScript. No comments yet...

I was shocked to discover that finding a JavaScript library to work with browser cookies isn’t as easy as I expected. So I’m rolling my own solution.

This code allows to access cookies directly by name or an alias.

var Cookies = {
	aliases: {},

	alias: function(alias, name, defaultValue)
	{
		Cookies.aliases[alias] = name;

		Cookies[alias] = function(value, days)
		{
			if(value == null)
				return Cookies.get(name, defaultValue);
			else
				Cookies.set(name, value, days);
		}
	},

	set: function(name, value, days)
	{
		name = Cookies.aliases[name] || name;

		var expires = '';

		if(!isNaN(days))
		{
			var date = new Date();
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
			expires = "; expires=" + date.toGMTString();
		}

		document.cookie = name + "=" + escape(value) + expires + "; path=/";
	},

	get: function(name, defaultValue)
	{
		name = Cookies.aliases[name] || name;

		var regex = new RegExp(name + "s*=s*(.*?)(;|$)");
		var cookies = document.cookie.toString();
		var match = cookies.match(regex);

		if(match)
			return unescape(match[1]);

		return defaultValue;
	},

	erase: function(name)
	{
		Cookies.set(name, '', -1);
	}
}

// Create an alias for a cookie named 'a'
Cookies.alias('greeting', 'a', 0);

// Set the value
Cookies.greeting(parseInt(Cookies.greeting()) + 1);

// Display the value
alert(
	Cookies.greeting() + 'n' +
	Cookies.get('a') + 'n' +
	Cookies.get('greeting')
);
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet, be the first one!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr