从 iFrame/Window 访问 JavaScript 中的父对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9774277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:48:10  来源:igfitidea点击:

Access parent object in JavaScript from iFrame/Window

javascriptiframeparent-child

提问by user823527

How do I access a global object or array defined in a parent window in the child window.

如何访问子窗口中父窗口中定义的全局对象或数组。

<script>
    var events_data;
    function function_to_fill_events_data () {
      .
      .
      .
    }
</script>

<div>
    <div><iframe src="mini.php" width:100%; height: 100%;" scrolling="no"></iframe> </div>
</div>

When I am in the mini document I'd like to be able to access the events_data variable in a javascript function.

当我在迷你文档中时,我希望能够访问 javascript 函数中的 events_data 变量。

回答by James Hill

Option 1

选项1

Your title mentions a child window. If you have a child window, and not an iframe, use this:

你的标题提到了一个子窗口。如果您有一个子窗口,而不是 iframe,请使用以下命令:

window.opener.events_data

Check out window.openeron MDN.

window.opener在 MDN 上查看。

Option 2

选项 2

Your code indicates that you're using an iframe. From an iframe, simply use parent:

您的代码表明您正在使用 iframe。从 iframe 中,只需使用parent

parent.events_data;

Check out window.parenton MDN.

window.parent在 MDN 上查看。



window.opener- Returns a reference to the window that opened this current window.

window.opener- 返回对打开当前窗口的窗口的引用。

window.parent- When a window is loaded in an , , or , its parent is the window with the element embedding the window.

window.parent- 当一个窗口在 、 或 中加载时,其父窗口是元素嵌入窗口的窗口。