Sergi
Sergi

Reputation: 1240

Different localStorage Objects and how to acces them

I am trying to use localStorage to get the value from a form and fill some fields of a second form on a second page. The storing fields part works well but on the second page, there is an iframe and apparently it uses localStorage. When I try to use localStorage on the second page it retrieves the values from this "second" localStorage instead.

    // This displays the correct localStorage info, so on page load, it seems to only be 1 localStorage
    console.log(localStorage);

    // Retrieve session storage fields
    // This comes back as null, second localStorage is loaded?
    var firstName = localStorage.getItem('firstName');
    var lastName = localStorage.getItem('lastname');
    var eMail = localStorage.getItem('eMail');
    var phone = localStorage.getItem('phone');
    var company = localStorage.getItem('company');
    var companyRole = localStorage.getItem('companyRole');

    // This does not work as a result
    j('#first-name').val(firstName);
    j('#last-name').val(lastName);
    j('#phone').val(phone);
    j('#eMail').val(eMail);

When I check the localStorage Object under the "application" Chrom tab, I see 2 Objects and inspecting the first one, I do see my data...I haven't found anything about how to access a different localStorage Object, is that even possible?

Upvotes: 1

Views: 1456

Answers (2)

Cameron Tinker
Cameron Tinker

Reputation: 9789

Local and session storage are specific to the origin. For example, the following origins would produce different local and session storage objects:
https://example.com/
http://example.com/

Even though they are the same domain, they have different protocols. This makes them different origins.

If you do not own the iframe's domain, there is no method for reading or modifying cross-origin storage from your own application. The other origin would need to receive a request to modify storage.

Upvotes: 1

Ricardo Rocha
Ricardo Rocha

Reputation: 16266

As you can check in here:

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

So, if the domain of the page and iframe are the same, so the localstorage data. This means that the localstorage data is saved by domain, and you can CRUD them independently if the code is inside of the main page or the iframe.

But, it also means that if the page is in a different domain than the iframe, you can only access the localstorage of the respective domain. For instance, if your javascript code is inside of an iframe, you cannot access to the localstorage of the main page and vice-versa.

Upvotes: 1

Related Questions