0

I ask this because I cannot get the browser to recognize, using a content script "foreground.js" in a Chrome Extension I'm building, any element by getElementsByTagName or getElementById with the js code I'm using, within a certain <iframe> on a page NOT under my control. I keep getting Cannot read properties of undefined on the console.

The code works fine on any WYSIWYG editor. Basically, it's this:

window.onload = function() {
var iframe = document.getElementsByTagName("iframe")[0];
////////////// - BY TAG THROUGH IFRAME BUTTON
iframe.contentDocument.getElementById("learntocode_searchbtn").addEventListener("click", function () {
var elmnt = iframe.contentDocument.getElementsByTagName("h1")[0];
var injectedStuff = document.createElement("element");
injectedStuff.innerHTML = "<br/><b>THIS IS BY TAG AND IFRAME!!</b>";
elmnt.append(injectedStuff);
    });
};

I was wondering if the issue is this: I can clearly see the <iframe> if on the page I choose "Inspect" > "Elements". But when I go to "Page Source" it is not there, although I can see some Javascript frame related code, so I assume the <iframe> is being injected somehow and is not at the source level.

Could this be the issue? Or maybe after the browser renders the source HTML and JS it does not matter if the <iframe> is at the source level or not since it is part of the DOM structure. If so then what could I be missing?

Verminous
  • 490
  • 3
  • 14

1 Answers1

1

Does an iframe need to be at the source HTML level to be able to identify it using "getElementsByTagName" or "getElementById"?

No. It needs to be in the DOM at the time you search the DOM for it.

You can have an iframe in the HTML, then remove it from the DOM with JS and then you wouldn't be able to find it with getElementsByTagName.

You can have an iframe added to the DOM by JS, but you don't find it if you search the DOM for it before it has been added.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • In this case I believe it is injected by JS on page load. The iframe is always there when I look at the DOM structure. Bogs my mind why I cannot get it with ```getElementsByTagName.```. Than you for your reply btw. But my code is also onload. Should I add ```setTimeout``` and wait for DOM to get fully structured and then proceed with the rest? – Verminous Oct 25 '22 at 11:15
  • How to make sure the code trying to find the iframe is only activated after the JS creates the iframe? Because I'm still not able to get that iframe. I tried everything now. – Verminous Oct 26 '22 at 22:45
  • Start by analysing the code that creates the frame, then work backwards from there. – Quentin Oct 27 '22 at 18:12
  • Hey @Quentin Yes I did that and found the iframe is nested in shadow Dom. I placed a new question regarding this here: https://stackoverflow.com/questions/74225479/how-to-capture-iframe-nested-within-shadow-doms-shadow-root-open-element in case you'd like to have a look. – Verminous Oct 27 '22 at 19:12