获取 iframe 的文档对象 [英] Getting the document object of an 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.
注意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
这篇关于获取 iframe 的文档对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!