简体   繁体   中英

access iframe with DOM

In the following code, the alert works fine and prints "DIV : IFRAME" as it should however it then says that cNs[1].childNodes[1].document has no properties.

Html:

<div id="WinContainer">
 <div style="display: none;"><iframe id="frame1" name="frame1"></iframe></div>
 <div style="display: none;"><iframe id="frame2" name="frame2"></iframe></div>
</div>

JavaScript:

var cNs = document.getElementById('WinContainer').childNodes;
alert(cNs[1].tagName + ' : ' + cNs[1].childNodes[1].tagName);
cNs[1].childNodes[1].document.location = 'someurl.pl';

BUT if I do this:

frame1.document.location = 'someurl.pl';

it works fine.

The iframe DOM node has a property called contentDocument which will be the equivalent of document , but for that iframe .

If the page being displayed is on another server tho (or even on a different port on the same server) you will get a security exception trying to access it.

Not sure if this works for IE.

I'm not all that familiar with javascript but it looks like you're using cNs incorrectly. It looks as though it is an array containing the child nodes and the code

cNs[1].childNodes[1].document.location = 'someurl.pl';

is trying to get the child nodes that do not exist. Try this it might work.

cNs[1].document.location = 'someurl.pl';

EDIT: frame1 should be:

cNs[0].childNodes[0].document.location

Remember that things are 0 indexed.

您还可以引用可靠的contentWindow属性,以如下方式获取该iFrame的文档对象:

cNs[0].childNodes[0].contentWindow.document

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