Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a javascript object in HTML5 local storage

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?

like image 566
Dheeraj R Avatar asked Sep 02 '25 09:09

Dheeraj R


2 Answers

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);
}
like image 99
Sudarshan Avatar answered Sep 04 '25 23:09

Sudarshan


Local storage will only store strings. If you can't make a string representation of your object, then you can't store it.

like image 24
alex Avatar answered Sep 04 '25 23:09

alex