我在文档中有如下元素,我可以通过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>
最佳答案
如果内容与查询它的脚本具有相同的协议(protocol)、域和端口号,则您只能查询 iframe 中的内容。它叫做SAME ORIGIN
如果是这样,那么这段代码将显示内容。如果不是 - 您无法从普通 html 页面中的普通脚本访问 iframe
Demo - 在 IE8、Chrome 13 和 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 - 如何在 Javascript 中获取 iframe 元素内的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7836563/