Accessing iframe's parent localstorage variable from iframe

后端 未结 1 1941
野的像风
野的像风 2021-01-18 11:24

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 localstora

相关标签:
1条回答
  • 2021-01-18 12:13

    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.

    0 讨论(0)
提交回复
热议问题