I am trying to inject an HTML element into an iframe in a page not under my control, after a button inside this iframe is clicked. To do this I use a Chrome Extension. The code is in a content script of the extension. The content of the iframe is in the same domain as the body/main document.
I am not able to get the iframe from the page using variations of getElement(s)By...
.
The page has 2 iframes, the main one is at the top of the DOM structure. I can see it perfectly when inspecting the elements. I need to get the "click" event from a button inside this iframe. But that iframe is returning as null
if I try getElementById
, and undefined
if I try with getElementsByTagName
. I tried to wait for the full load of the page with setTimeout(
, window.onload = function () {
, window.addEventListener('load', function () {
combinations of this etc. My last attempt was this:
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
checkIframeLoaded();
}else{
document.addEventListener('DOMContentLoaded', function () {
});
}
}
function checkIframeLoaded() {
if(document.getElementsByTagName('body')[0]) {
let iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe);
iframe.contentDocument.getElementById("dd7975c81b0fac90f6bba640604bcb96").addEventListener("click", function () {
alert("HURRAY!");
});
};
}
No matter what I do I cannot get the iframe detected. What am I doing wrong?
E D I T :
I suspect that the fact that iframe is buried within other "exotic" tags might make this iframe not detectable by normal means. I can see parent tags which are by order from parent to child:
<body...>
<macroponent-f51912f4c700201072b211d4d8c26010...>
#shadow-root (open)
<div...>
<sn-canvas-appshell-root...>
<sn-canvas-appshell-layout...>
<sn-polaris-layout...>
<iframe...>
<-- I need to listen to click of a button inside an iframe, but the iframe is not detected.
<button...>
Some of these tags might be working as if they were another iframe? Meaning that I should try to get the iframe I want as if it was within another iframe? Or are these tags something else and the solution is different?
Also from seeing other questions it seems #shadow-root (open)
might be an issue here.