简体   繁体   English

使用Javascript访问父级中的iframe变量

[英]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. 我知道在Stack Overflow上已经有令人难以置信的类似问题,但是我尝试了其中的许多问题,却一无所获。 I'm trying to grab a variable from the child iframe to use in the parent window. 我正在尝试从子iframe抓取一个变量以在父窗口中使用。

In child.html head tag 在child.html头标记中

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

In parent.html 在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. 而且无论我尝试什么,我都无法获得滚动以从子iframe中获取myVar变量。 This is nearly verbatim of examples on Stack Overflow and other forums that people say work perfectly; 这几乎是Stack Overflow和其他论坛上人们常说完美的例子。 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. 当页面在iframe中加载时,尝试从子内部访问oad()。

Add in child: 添加子项:

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

Also, you can change the code to pass and get the variable as parameter in load(prm) . 另外,您可以更改要传递的代码,并在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. 仍然我认为在iframe上使用name =“ ...”有点怪异,我会使用ID,但这似乎不会影响chrome,并且我可以通过父项或子项上的onload访问变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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