问题描述
我在文档内部有一个如下所示的元素,我可以通过 document.getElementById('iframe_id')
获得iframe元素,但是如何在该iframe中获得该元素呢?我尝试了 iframeElement.contentWindow
,返回的 DOMWindow
没有属性.还尝试了 iframeElement.docuemnt
和 iframeElement.contentDocument
,它们都是未定义的.我怎么才能得到它?我在实验中使用的是最新的Chrome.
I have a element as below inside the document, I could get the iframe element by document.getElementById('iframe_id')
, but how to get the element inside this iframe? I tried iframeElement.contentWindow
, and the returned DOMWindow
has no properties. Also tried iframeElement.docuemnt
and iframeElement.contentDocument
, both of them are undefined. How can I get it? I am using the latest Chrome in my experiment.
这是iframe元素
<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>
推荐答案
如果内容与用于询问的脚本具有相同的协议,域和端口号,则只能在iframe中询问内容.它称为相同来源
You can ONLY interrogate content in an iframe if the content has the same protocol, domain and port number as the script that interrogates it. It is called SAME ORIGIN
如果是这种情况,那么此代码将显示内容.如果不是,则无法从普通的html页面中的普通脚本访问iframe
If that is the case, then this code will show the content. If not - you cannot access the iframe from a normal script in a normal html page
演示-在IE8,Chrome 13和Fx6中进行了测试
Demo - tested in IE8, Chrome 13 and Fx6
function showIframeContent(id) {
var iframe = document.getElementById(id);
try {
var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;
alert(doc.body.innerHTML);
}
catch(e) {
alert(e.message);
}
return false;
}
<iframe id='iframe_id1' src="javascript:parent.somehtml()"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id1')">Show</a>
<hr/>
<iframe id='iframe_id2' src="http://plungjan.name/"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id2')">Show</a>
<hr/>
这篇关于如何在Javascript的iframe元素中获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!