我在文档中有一个元素,如下所示,我可以通过document.getElementById('iframe_id')获得iframe元素,但是如何获得这个iframe中的元素呢?我尝试了iframeElement.contentWindow,返回的DOMWindow没有任何属性。我还尝试了iframeElement.docuemnt和iframeElement.contentDocument,它们都是未定义的。我怎么才能得到它呢?我在我的实验中使用了最新的Chrome。
下面是iframe元素
<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>发布于 2011-10-20 21:30:12
仅当内容具有与查询它的脚本相同的协议、域和端口号时,才能查询iframe中的内容。它被称为SAME ORIGIN
如果是这种情况,则此代码将显示内容。否则,您将无法从普通html页面中的普通脚本访问iframe。
Demo -在IE8、Chrome13和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/>https://stackoverflow.com/questions/7836563
复制相似问题