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?
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);
}
Local storage will only store strings. If you can't make a string representation of your object, then you can't store it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With