SameShirtEveryDay.com

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

Storing data localy with JavaScript

Posted on June 2nd, 2007 by Alex Gorbatchev. In JavaScript, Web Development. 1 comment so far...

Sometimes you just want to store some data on the client to access it later. Sometimes you don’t even want to send it to the server. In this case, you can use something called ‘local storage’.

In Firefox it utilizes window.globalStorage which is a part of HTML 5 draft. Internet Explorer, unsurprisingly had this ability since version 5 using #default#userData behavior and unsurprisingly it’s somewhat awkward. Unfortunately, Safari/Webkit don’t seem to support local storage at all as of now, so this is more of a demo.

<html>
<body>

<script>
LockBox = {
	ensureStorage: function()
	{
		if(LockBox.storage != null)
			return;

		var storage;

		if(document.all)
		{
			storage = document.createElement("span");
			storage.style.behavior = "url(#default#userData)";

			if(document.body)
				document.body.appendChild(storage);
			else
				throw new Error("DomStorage works only after dom loaded");

			storage.load("lockbox");
		}
		else
		{
			storage = globalStorage[location.hostname];
		}

		LockBox.storage = storage;
	},

	set: function(name, value)
	{
		LockBox.ensureStorage();

		if(document.all)
		{
			LockBox.storage.setAttribute(name, value);
			LockBox.storage.save("lockbox");
		}
		else
		{
			LockBox.storage[name] = value;
		}
	},

	get: function(name, defaultValue)
	{
		LockBox.ensureStorage();

		var result = document.all
			? LockBox.storage.getAttribute(name)
			: LockBox.storage[name]
		;

		return result || defaultValue;
	}
}

//
// Here's a little demo.
//
var value = parseInt(LockBox.get('count', 0));
alert(value);
LockBox.set('count', value + 1);
</script>

</body>
</html>
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.

One comments so far...

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