Accessing Iframe Variable in Parent With Javascript

こ雲淡風輕ζ 提交于 2019-12-13 03:59:16

问题


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.



来源:https://stackoverflow.com/questions/10622061/accessing-iframe-variable-in-parent-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!