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?