【问题标题】:Get IFrame's document, from JavaScript in main document从主文档中的 JavaScript 获取 IFrame 的文档
【发布时间】:2011-04-29 06:50:23
【问题描述】:

我有这个 HTML 代码:

<html>
  <head>
    <script type="text/javascript">
      function GetDoc(x)
      {
        return x.document ||
          x.contentDocument ||
          x.contentWindow.document;
      }

      function DoStuff()
      {
        var fr = document.all["myframe"];
        while(fr.ariaBusy) { }
        var doc = GetDoc(fr);
        if (doc == document)
          alert("Bad");
        else 
          alert("Good");
      }
    </script>
  </head>
  <body>
    <iframe id="myframe" src="http://example.com" width="100%" height="100%" onload="DoStuff()"></iframe>
  </body>
</html>

问题是我收到消息“坏”。也就是说iframe的文档没有正确获取,GetDoc函数返回的其实是父文档。

如果你能告诉我我的错误在哪里,我将不胜感激。 (我想将文档托管在 IFrame 中。)

谢谢。

【问题讨论】:

  • 这是 2010 年提出的,今天是 2015 年,这在任何更新的浏览器中都不起作用,除非您正在开发 google.com。由于跨源策略,如果 iframe 指向的页面与加载原始文档的域不同,则您无法访问它的内容。

标签: javascript html iframe document


【解决方案1】:

您应该能够使用以下代码访问 IFRAME 中的文档:

document.getElementById('myframe').contentWindow.document

但是,如果框架中的页面是从不同的域(例如 google.com)加载的,您将无法执行此操作。这是因为浏览器的Same Origin Policy

【讨论】:

  • 嗯?这将返回undefined(大多数浏览器)或&lt;iframe&gt;元素所在的文档(IE),这正是OP想要解决的问题。
  • 哎呀,我想这就是我没有先测试它的结果:-/。我刚刚对其进行了编辑以添加 contentWindow 引用。
  • 请注意iframe.contentDocument == iframe.contentWindow.document
【解决方案2】:

问题在于,在 IE 中(我假设您正在测试),&lt;iframe&gt; 元素有一个 document 属性,它引用包含 iframe 的文档,并且在 @ 987654323@ 或 contentWindow.document 属性。你需要的是:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

另外,document.all 并非在所有浏览器中都可用,并且是非标准的。请改用document.getElementById()

【讨论】:

    【解决方案3】:

    万一出现跨域错误:

    如果您可以控制 iframe 的内容 - 也就是说,如果它只是在 Amazon Mechanical Turk 等跨域设置中加载 - 您可以使用内部 html 的 &lt;body onload='my_func(my_arg)'&gt; 属性来规避这个问题.

    例如,对于内部 html,使用this html 参数(是的 - 定义了this,它指的是内部主体元素的父窗口):

    &lt;body onload='changeForm(this)'&gt;

    在内部 html 中:

        function changeForm(window) {
            console.log('inner window loaded: do whatever you want with the inner html');
            window.document.getElementById('mturk_form').style.display = 'none';
        </script>
    

    【讨论】:

      【解决方案4】:

      你也可以使用:

      document.querySelector('iframe').contentDocument
      

      【讨论】:

        猜你喜欢
        • 2014-02-23
        • 2011-12-25
        • 2012-11-14
        • 2011-11-26
        • 2013-04-17
        • 2014-05-26
        • 2018-05-17
        • 2022-01-20
        • 1970-01-01
        相关资源
        最近更新 更多