Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
Le Qs Avatar asked Sep 04 '16 23:09

Le Qs


People also ask

Can iframe access parent localStorage?

localstorage is a property of the domain 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.

Can iframe access parent document?

It's still possible to access the parent from within a frame provided that the domains match. The variables parent and top can be overwritten (usually not intended). It's safer to use window.

Does iframe share local storage?

According to the W3C: Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data. In other words, if the iframes all reside in the same domain, then they will share the same local storage instance.


1 Answers

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.

like image 107
Chris Simon Avatar answered Sep 28 '22 07:09

Chris Simon