从主文档中的 JavaScript 获取 IFrame 的文档 [英] Get IFrame's document, from JavaScript in main document

查看:23
本文介绍了从主文档中的 JavaScript 获取 IFrame 的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 HTML 代码:

I have this HTML code:

<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>

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

The problem is that I get message "Bad". That mean that the document of iframe is not got correctly, and what is actualy returned by GetDoc function is the parent document.

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

I would be thankful, if you told where I do my mistake. (I want to get document hosted in IFrame.)

谢谢.

推荐答案

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

You should be able to access the document in the IFRAME using the following code:

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

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

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

这篇关于从主文档中的 JavaScript 获取 IFrame 的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆