Question

I am writing a web page that should store persistent data. In IE, I can simply use Userdata Behavior to store data or objects. Besides, Userdata Behavior offers getAttribute and setAttribute methods to customize the stored objects.

But it is not supported by firefox. With localStorage, I can only store strings with a unique key. My question is: is it possible to customize objects stored in localStorage by using similar methods, like getAttribute or setAttribute?

I want to convert the following code to a new one that should wok under firefox by using localStorage. But I have no idea, how to convert the setAttribute and getAttribute methods. Any idea? Thanks a lot in advance.

<style type="text/css">
.storeuserData {
behavior: url(#default#userData);
</style>
<script type="text/javascript">
function fnSaveInput(){
   var oPersist=oPersistForm.oPersistInput;
   oPersist.setAttribute("sPersist",oPersist.value);
   oPersist.save("oXMLBranch");
}
function fnLoadInput(){
   var oPersist=oPersistForm.oPersistInput;
   oPersist.load("oXMLBranch");
   oPersist.value=oPersist.getAttribute("sPersist");
}
</script>
</head>

<body>

<form id="oPersistForm">
    <input class="storeuserData" type="text" id="oPersistInput">
    <input type="button" value="Load" onclick="fnLoadInput()">
    <input type="button" value="Save" onclick="fnSaveInput()">
</form>
Was it helpful?

Solution

I don't really know a whole lot about the IE implementation but for local storage you could try something like this:

function setDataValue(attr, value){
   //If local stoarge var doesn't exist, create it
    if(typeof window.localStorage.mydata == 'undefined') window.localStorage.mydata = '{}';
    //Read data from local storage in to object
    var data = JSON.parse(window.localStorage.mydata);
    //update object
    data[attr] = value;
    //save object back in to local storage
    window.localStorage.mydata = JSON.stringify(data);
}
function getDataValue(attr){
    return JSON.parse(window.localStorage.mydata)[attr];
}

Basically all the two functions above do is read & write to a JavaScript object stored in localstorage (encoded as JSON for storage purposes)

Your function's could then be written as:

function fnSaveInput(){
    var oPersist=oPersistForm.oPersistInput;
    setDataValue('sPersist', oPersist.value);
}
function fnLoadInput(){
    var oPersist=oPersistForm.oPersistInput;
    oPersist.value = getDataValue('sPersist');
}

Please note, i wrote all this code freehand so there could be a few typos/errors in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top