Storing a javascript object in HTML5 local storage

html, javascript, local-storage

Solution

You have to first convert the object into json and then store in local storage. And when you want to reuse the stored data you have to deserialize the json string into javascript object and it will work fine.

Working Sample

function setValue() {
    var obj = new user();
    var jsonObject = JSON.stringify(obj);
    sessionStorage.setItem("Gupta", jsonObject);
    getValue();
}

function user() {
    this.Name = "rahul";
    this.Age = 20;       
}

function getValue() {
    var json_string = sessionStorage.getItem("Gupta");
    var obj = JSON.parse(json_string)
    alert("Name = "+obj.Name + ", Age = " + obj.Age);
}

Problem

I want to store a JavaScript object in HTML5 local storage. ``` sessionStorage.setItem("localObj",this); ``` I am using the above statement within a function.The object contains HTML tags. I can neither convert it to a string nor to a JSON. How do i proceed with this?

Original source

Related problems