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

查看:85
本文介绍了从主文档中的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.)

谢谢。

Thank you.

推荐答案

您应该可以使用以下代码访问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天全站免登陆