appleris
appleris

Reputation: 3

Global object not retrieved when stored in localStorage

I am trying to store a global object in localStorage on page1 which runs for around 4 seconds and then redirects me to a new page eg: page2.

For storing global object in page1 to localStorage I use:

Page1-- xyz.site.com/myCode.html

window.my_global_object = {
property1: "abc",
property2: "pqr"
}

window.localStorage["my_storage_vals"] = my_global_object;

Page2: mylocal/page2.html

var retrievedObject = window.localStorage["my_storage_vals"];
                            alert(retrievedObject);

But still I cannot see my object being stored. It's still undefined. I want to maintain the state of my globalObject on Page2 . Not on page3 or page4 etc .. . I want to save the values only on page2.

Using json.stringify

var val = JSON.stringify(my_global_object);
            localStorage.setItem("myVal",val);

var retrievedObject = localStorage.getItem("myVal");
                            alert(retrievedObject);

Upvotes: 0

Views: 38

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69346

You said that your pages are:

  1. xyz.site.com/myCode.html
  2. mylocal/page2.html

The localStorage object is bound to the local domain, so xyz.site.com will have a totally different localStorage than mylocal. Hence, if you set a property in the first page and then redirect to another site, the localStorage will not be the same anymore, and you'll not have access to your property.

To work around this you should either:

  • Put both pages on the same domain
  • or call the second page passing some query string in the url
  • or implement an XMLHttpRequest from the second to the first page.

Upvotes: 1

Related Questions