10

I have this page https://jsfiddle.net/r91bLb7r/9/ which I am using to display this iframe https://jsfiddle.net/r91bLb7r/8/.

The parent page has a value in localstorage that I want to access from the iframe.

This is the parent's code:

$(document).ready(function () {
    $( "#top" ).click(function() {
        localStorage.setItem("parent", "one");
        alert('I am the top page');
    });
});

This is the iframe code:

$(document).ready(function () {
    $( "#map" ).click(function() {
        var mode = localStorage.getItem("parent");
        alert('I am the iframe'+mode);
    });
});

How can I access the parent's localstorage value from the iframe?

nateyolles
  • 1,851
  • 5
  • 17
  • 23
Le Qs
  • 785
  • 2
  • 9
  • 26

1 Answers1

30

localstorage is a property of the domain

localstorage isn't a property of the page or iframe, but a property of the domain. If your main page and iframe are from the same domain, they will be able to access the same localstorage

In your jsfiddle example, you would expect it to work, because they are both from jsfiddle.net - but you are being caught out by a trick of how jsfiddle works - the bottom-right box that actually executes is actually an iframe itself, being loaded from a different domain: fiddle.jshell.net

So on the parent, the execution window page is from fiddle.jshell.net and the iframe is from jsfiddle.net, as per your hardcoded iframe src - they are different domains and can't access each other's localstrage.

If you alter the parent iframe src to be https://fiddle.jshell.net/r91bLb7r/8/show/ (the fiddle.jshell.net URI assocated with your iframe's jsfiddle), then you'll find it works as expected.

If your real-world case has the two pages being loaded from different domains, then they will not be able to access each other's local storage - if they are from the same domain, you shouldn't have a problem.

Chris Simon
  • 6,185
  • 1
  • 22
  • 31
  • Thanks for your length answer. – Le Qs Sep 05 '16 at 00:14
  • Is there an alternative to share data when main page and iframe are from different domains? – BEAGLE Jun 03 '22 at 15:04
  • @BEAGLE As I understand it, you cannot _read_ another iframe's content from a different domain, but iframes are allowed to _write_ messages to each other. See [here](https://stackoverflow.com/questions/52047205/how-to-use-postmessage-on-iframe). Slight aside, I would also recommend reading [this](https://www.verygoodsecurity.com/blog/posts/iframes-as-a-security-feature). – Colm Bhandal Jun 11 '22 at 11:30