Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - Accessing iframe's parent localstorage variable from iframe

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...