从iframe访问父窗口元素

Accessing parent window elements from iframe

本文关键字:窗口 元素 访问 iframe      更新时间:2023-09-26
  • 我有一个带有iframecustomer.jsp页面
  • iframe有一个按钮。单击按钮后,我需要访问customer.jsp页面内的对话框
  • 我尝试了window.parent.document.getElementById('formDialog');,但得到了null
window.parent.document.getElementById('target'); 

两个资源应该在同一来源上

对于跨来源资源,iframe和父文档之间的通信是不可能的。只有当iframe和包含页面来自同一主机、端口和协议时,它才会工作——例如。http://example.com:80/1.html和http://example.com:80/2.html

 Assuming both resources are from the same origin

在iframe中,window.parent指的是父文档的全局对象,而不是文档对象本身。我认为您需要使用parent.document.getElementById('formDialog')

您可以通过parent.document.getElementById('formDialog'); 访问父窗口元素

如果你得到null,你能在Iframes父级的上下文中得到那个元素吗?您是否引用了正确的ID和正确的父级?

试试这个。希望这能有所帮助。假设我通过点击iframe中的某个按钮获得了CallParentFunction。

function CallParentFunction(){
     if (top && top.opener && top.opener.top) {
        top.opener.document.getElementById('formDialog'); 
     }
      else {
        top.document.getElementById('formDialog'); 
     }
}