简体   繁体   中英

Get DOM element in an iframe in JavaScript

I have two documents, one of which is embedded into the other with an iframe. I'm trying to use this code to access the img tag inside the iframe, however, I cannot use the document.getElementById function on the iframe element:

iframes = document.getElementsByTagName("iframe")
spaces = iframes[0].contentWindow.document;
spaces = spaces.getElementsByTagName("img")
for (var i=0, max=spaces.length; i < max; i++) {
     alert(spaces[i].innerHTML)
}
alert(spaces)
var x = document.getElementById("frame");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
alert(y.body.innerHTML)

spaces returns [object HTMLCollection] and y returns [object HTMLDocument]

So, if you're on the same domain as your iframe content, you can use

document.getElementById('my-iframe').contentWindow.document.getElementById(...)

If you're not on the same domain, you can't access/manipulate iframe content for security reasons. Otherwise malicious folks could throw up an iframe that looks like Facebook or something and steal other folk's info.

If you're not on the same domain but own both domains you're using, you can set up messaging between the two frames. And use the parent to message the child for information/manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM