What I Had To Do To Access iFrame DOM Elements AFTER MANY FAILURES
I was working on a simple proof of concept for making sure I could manipulate DOM elements inside an iframe using JavaScript loaded for the main page.
I am not concerned with accessing cross domain pages in the iframe in my work.
First, my simple main page ... NOTE I am using class="test-outer"
as the class my JavaScript will query.
<!DOCTYPE html>
<html>
<head>
<title>My Outer Page</title>
</head>
<body>
<h1>This is the <span class="test-outer">outer</span> page</h1>
<hr />
<iframe
id="the_iframe"
src="./Test_1_inner.html"
height="500px"
width="1000px"
title="My Inner Page"
style="border: none"
>
</iframe>
</body>
<script src="script.js" defer></script>
</html>
Next is my inner page that will go in the iframe ... NOTE I am using class="test-inner"
as the class my JavaScript will query.
<!DOCTYPE html>
<html>
<head>
<title>My Inner Page</title>
</head>
<body>
<h1>
This is the
<span class="test-inner">INNER</span>
page
</h1>
</body>
</html>
Now for the important part - the JavaScript. NOTE my use of a setTimeout, which was the MAIN thing that got my prototype here to a working state.
"use strict";
const field = document.querySelector(".test-outer");
field.addEventListener("click", function (e) {
console.log("Field");
});
let seconds = 0.0;
let iframe_timer = setTimeout(function () {
let the_iframe = document
.querySelector("iframe")
.contentDocument.querySelector(".test-inner");
if (the_iframe === null) {
console.log("iframe failed to load");
seconds += 0.25;
if (seconds > 3.0) {
my_timer_stopper();
}
} else {
console.log("iframe loaded");
my_timer_stopper();
the_iframe = document
.querySelector("iframe")
.contentDocument.querySelector(".test-inner");
the_iframe.addEventListener("click", function (e) {
console.log("Token");
});
}
}, 250);
function my_timer_stopper() {
clearTimeout(iframe_timer);
}
Finally, the console log minus things you wouldn't want to see from that.
iframe loaded
script.js:27 Token // from clicking on INNER in the iframe
script.js:6 Field // from clicking on outer in the main page
script.js:27 Token // from clicking on INNER in the iframe
I hope this saves some readers a lot of time that I had to waste to figure this out :-)