Javascript 从 iframe 访问父窗口元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14972587/
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
Accessing parent window elements from iframe
提问by Rachel
- I have a
customer.jsppage with aniframe. iframehas a button. on click of the button, i need to access a dialog box which is insidecustomer.jsppage.- I tried
window.parent.document.getElementById('formDialog');but am gettingnullvalue.
- 我有一个
customer.jsp带有iframe. iframe有一个按钮。单击按钮后,我需要访问customer.jsp页面内的对话框。- 我尝试过,
window.parent.document.getElementById('formDialog');但正在获得null价值。
回答by Talha
window.parent.document.getElementById('target');
both resources should be on same origin
两个资源应该来自同一来源
回答by Bhushan Firake
Communication between an iframe and parent document is not possible for cross-origin resources. It will only work if the iframe and the containing page are from the same host, port and protocol - e.g. http://example.com:80/1.htmland http://example.com:80/2.html
iframe 和父文档之间的通信对于跨源资源是不可能的。仅当 iframe 和包含页面来自相同的主机、端口和协议时才有效 - 例如http://example.com:80/1.html和http://example.com:80/2.html
Assuming both resources are from the same origin
In the iframe, window.parent refers to the global object of the parent document, not the document object itself. I believe you would need to use parent.document.getElementById('formDialog')
在 iframe 中,window.parent 指的是父文档的全局对象,而不是文档对象本身。我相信你需要使用parent.document.getElementById('formDialog')
回答by novalagung
seems like you forgot something in your code. try this:
好像您忘记了代码中的某些内容。尝试这个:
window.parent.window.document.getElementById('formDialog');
回答by Bryan Huang
You can access parent window elements through parent.document.getElementById('formDialog');
您可以通过访问父窗口元素 parent.document.getElementById('formDialog');
If you get null are you able to get that element within the context of that Iframes parent? Are you referencing the right ID and the right parent?
如果您获得 null,您是否能够在该 Iframes 父项的上下文中获取该元素?您是否引用了正确的 ID 和正确的父级?
回答by Jobert Enamno
Try this. Hope this helps. Let's say I have CallParentFunction from button click of a button in an iframe.
尝试这个。希望这可以帮助。假设我通过单击 iframe 中的按钮获得了 CallParentFunction。
function CallParentFunction(){
if (top && top.opener && top.opener.top) {
top.opener.document.getElementById('formDialog');
}
else {
top.document.getElementById('formDialog');
}
}

