Accessing Iframe Variable in Parent With Javascrip

2019-08-17 00:28发布

问题:

I'm aware there are incredibly similar questions on Stack Overflow already for this, but I've tried MANY of them, and am just getting nothing. I'm trying to grab a variable from the child iframe to use in the parent window.

In child.html head tag

<script type="text/javascript">
    var myVar="1";
</script>

In parent.html

<script type="text/javascript">
function load()
{
    var scroll="0"; 
    scroll = window.myIframe.myVar;
    if (scroll == "0") DO SOMETHING;
    else DO SOMETHING ELSE;
}
</script>
<iframe src="child.html" name="myIframe" onload="load()">
<p>Your browser does not support iframes.</p>
</iframe>

And no matter what I try, I cannot get scroll to grab the myVar variable from the child iframe. This is nearly verbatim of examples on Stack Overflow and other forums that people say work perfectly; any ideas what I'm doing wrong?

Edit: They are on the same domain.

回答1:

Try to access oad() from inside child when the page loads in iframe.

Add in child:

<body onload="parent.load()">

Also, you can change the code to pass and get the variable as parameter in load(prm) .



回答2:

I tried your code offline and i get an error "unsafe access" while accessing

window.myFrame

local pages can be tricky, however when i put the same files online they work well, domains and ports match. still i think its a bit weird using name="..." on the iframe, i would be using ID, but that doesn't seem to bother chrome and i got access to the variable with either onload on parent or child.