获取iframe的文档对象 [英] Getting the document object of an iframe

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

问题描述

我正在尝试获取一个iframe的文档对象,但是没有一个我已经google的示例似乎有帮助。我的代码如下所示:

I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this:

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

我已经测试过,我能够获取iframe对象,但.document不起作用, .contentDocument也没有,我想我已经测试了一些其他的选项,但是所有这些都返回未定义的,甚至是应该是有效但是不适用于我的例子。所以我已经有了iframe对象,现在我想要的是它的文档对象。我已经在Firefox和Chrome上测试了这个。

I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.

推荐答案

尝试以下

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 所有主流浏览器都支持,所以这可能是最好的方法。

Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.

  • http://help.dottoro.com/ljctglqj.php

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

Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy


  • < a href =http://javascript.info/tutorial/same-origin-security-policy =noreferrer> http://javascript.info/tutorial/same-origin-security-policy

  • http://javascript.info/tutorial/same-origin-security-policy

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

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