获取iframe的文档对象

Dud*_*awg 46 javascript iframe dom

我正在尝试获取iframe的文档对象,但我用Google搜索的示例似乎都没有帮助.我的代码看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

我已经测试过我能够获取iframe对象,但是.document不起作用,.contentDocument和我认为我也测试了其他一些选项,但是所有这些都返回undefined,即使是应该的示例已经工作,但他们不适合我.所以我已经有了iframe对象,现在我想要的只是它的文档对象.我在Firefox和Chrome上测试过这一点无济于事.

Jar*_*Par 69

请尝试以下方法

var doc=document.getElementById("frame").contentDocument;

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

注意:AndyE指出contentWindow所有主流浏览器都支持,所以这可能是最好的方法.

注意2:在此示例中,您将无法通过任何方式访问该文档.原因是您无法访问具有不同来源的iframe文档,因为它违反了"同源"安全策略

  • AFAIK,所有浏览器都支持非标准的`contentWindow`属性,所以最安全的就是这样. (2认同)
  • @Andy E,@ JaredPar:我认为它是较旧的(3.0之前版本)Safari版本,不支持`contentWindow`但支持`contentDocument`.`contentDocument`在`contentWindow`(DOM 2与HTML5)之前很久就已成为一个标准,所以我过去常常支持它,但现在`contentWindow`本身就非常安全. (2认同)

Jam*_*ill 6

这是我使用的代码:

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();
Run Code Online (Sandbox Code Playgroud)

contentWindow与contentDocument

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


Dom*_*tin 6

为了更加健壮:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...
Run Code Online (Sandbox Code Playgroud)