获取iframe的文档对象

我试图获得一个iframe的文档对象,但没有一个我googlesearch的例子似乎帮助。 我的代码如下所示:

<html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> 

我已经testing了我能够获得iframe对象,但.document不起作用,.contentDocument也没有,我想我也testing了一些其他的选项,但是它们都返回未定义的,甚至是应该的已经工作,但他们不为我工作。 所以我已经有了iframe对象,现在我只想要它是文档对象。 我已经在Firefox和Chrome上testing过这个function。

尝试以下

 var doc=document.getElementById("frame").contentDocument; // Earlier versions of IE or IE8+ where !DOCTYPE is not specified var doc=document.getElementById("frame").contentWindow.document; 

注意:AndyE指出contentWindow是所有主stream浏览器都支持的,所以这可能是最好的select。

注2:在本示例中,您将无法通过任何方式访问文档。 原因是您不能访问具有不同来源的iframe文档,因为它违反了“相同来源”安全策略

这是我使用的代码:

 var ifrm = document.getElementById('myFrame'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); 

contentWindow与contentDocument

  • IE(Win)和Mozilla(1.7)将使用oIFrame.contentWindow返回iframe中的窗口对象。
  • Safari(1.2.4)不理解该属性,但确实有oIframe.contentDocument,它指向iframe中的文档对象。
  • 为了使它更加复杂,Opera 7使用了oIframe.contentDocument,但它指向了iframe的窗口对象。 由于Safari无法通过标准DOM直接访问iframe元素的窗口对象(或者是否),我们完全现代化的跨浏览器兼容的代码将只能访问iframe中的文档。

为了更加健壮:

 function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc && iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc && iframe_object.document) { doc = iframe_object.document; } if (doc && doc.defaultView) { return doc.defaultView; } if (doc && doc.parentWindow) { return doc.parentWindow; } return undefined; } 

 ... var el = document.getElementById('targetFrame'); getIframeWindow(el).targetFunction(); ...