简体   繁体   English

如何访问加载的 iframe 中的元素?

[英]How can I access an element in a loaded iframe?

I have a website with a donorbox button.我有一个带有捐赠箱按钮的网站。 When it's clicked, an iframe is added to the page as a modal.单击它时,iframe 将作为模态添加到页面中。 I want to access the elements in that iframe but I get an error Cannot read property 'click' of null when I try to click one of the buttons with a simple document.getElementsByClassName('db_button')[0].click();我想访问 iframe 中的元素,但是当我尝试使用简单的document.getElementsByClassName('db_button')[0].click(); Cannot read property 'click' of null command.命令。

Debugging in the console, I also get the same message until I inspect the element and then it seems to work fine.在控制台中调试时,我也会收到相同的消息,直到我检查元素,然后它似乎工作正常。 What am I doing wrong?我究竟做错了什么?

firstly, get your iframe element首先,获取您的 iframe 元素

document.getElementById('iframeId') or document.getElementsByTagName("iframe") document.getElementById('iframeId')document.getElementsByTagName("iframe")

the second expression will get a list object, get the iframe you need with index.第二个表达式将得到一个列表 object,用索引得到你需要的 iframe。

secondly, get inner document by this其次,通过这个获取内部文件

a.contentDocument || a.contentWindow.document

then do your search inside iframe's document.然后在 iframe 的文档中进行搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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