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...
I like your LockBox storage solution but … I have found a big problem with Firefox 3. The line
storage = globalStorage[location.hostname];
results in a security exception when the application is NOT launched through a web server but instead I simply doubleclick on a local file. Of course location.hostname is an empty string in my case. Any idea what should be used instead of location.hostname? I have tried ‘localdomain’, ‘localhost.localdomain’, path to my htm file, folder name of my htm file – nothing works and I always get a security exception (I placed try/catch block around the assignment). Please help.
Leave a Reply