Storing data localy with JavaScript
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>
One comments so far...
Leave a Reply