javascript 从 iFrame 读取父文档并更改父文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4733542/
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
Reading parent document from iFrame and changing parent
提问by MeanwhileInHell
I'm trying to write a JavaScript application that will load a button up in an iFrame on a page. This application will read the parent document and strip out all images, apply minimal styling and reload the parent with this newly marked up page.
我正在尝试编写一个 JavaScript 应用程序,它将在页面上的 iFrame 中加载一个按钮。此应用程序将读取父文档并删除所有图像,应用最小样式并使用这个新标记的页面重新加载父文档。
The problem I am having is reading and writing the parent document from the iFrame. Does anyone know of a way to achieve this? I've read up a little on cross-domain messaging but am unsure of the alternatives and which would be best.
我遇到的问题是从 iFrame 读取和写入父文档。有谁知道实现这一目标的方法?我已经阅读了一些关于跨域消息传递的内容,但不确定替代方案以及哪种方案最好。
Thanks in advance.
提前致谢。
回答by David M?rtensson
You can reference the parent either by using parent or using the top variable that always points to the outer most document.
您可以通过使用 parent 或使用始终指向最外层文档的 top 变量来引用父级。
- parent == parent window
- top == out most window
- 父 == 父窗口
- 顶部 == 最外面的窗口
So for accesing the first div in the parent window
所以为了访问父窗口中的第一个 div
var d = parent.document.getElementsByTagName("div")[0];
But as noted already in the comment, both the outer document and the document in the iframe need to be from the same domain or you will be blocked for security reasons.
但是正如评论中已经指出的那样,外部文档和 iframe 中的文档都需要来自同一个域,否则出于安全原因您将被阻止。

