如何在 Javascript 中获取 iframe 元素内的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7836563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the element inside an iframe element in Javascript?
提问by Thomson
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 元素document.getElementById('iframe_id')
,但是如何获取此 iframe 中的元素?我试过了iframeElement.contentWindow
,返回的DOMWindow
没有属性。也试过iframeElement.docuemnt
and iframeElement.contentDocument
,它们都未定义。我怎么才能得到它?我在实验中使用的是最新的 Chrome。
Here is the iframe element
这是 iframe 元素
<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>
采纳答案by mplungjan
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
如果内容与询问它的脚本具有相同的协议、域和端口号,则您只能询问 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
如果是这种情况,则此代码将显示内容。如果没有 - 您无法从普通 html 页面中的普通脚本访问 iframe
Demo- tested in IE8, Chrome 13 and Fx6
演示- 在 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/>
回答by R?zvan Flavius Panda
Having:
拥有:
var iframe = document.getElementById('iframe_id');
To get the content document you can use:
要获取内容文档,您可以使用:
var contDoc = iframe.contentDocument || iframe.contentWindow.document;
Then you can search for your element inside the iframe by id.
然后您可以通过 id 在 iframe 中搜索您的元素。
回答by dwalldorf
You should be able to access it by document.getElementById('yourIFrame').document.getElementById('yourElement')
您应该可以通过以下方式访问它 document.getElementById('yourIFrame').document.getElementById('yourElement')