简体   繁体   中英

Accessing Iframe Variable in Parent With Javascript

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.

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM