I'd like to create a JavaScript function that detects the addition of an iframe tag in the DOM, which manages to modify its src attribute before it can execute, so that it can execute with the new src attribute.
To try and achieve this, I used the MutationObserver interface like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MutationObserver Example</title>
</head>
<body>
<script>
function test() {
const config = {
subtree: true,
childList: true
};
const callback = (mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
for (const node of mutation.addedNodes) {
if (node.tagName && node.src && node.tagName.toLowerCase() === "iframe") {
node.src = "index8.html";
}
else {
for (const div of node.querySelectorAll?.("div") || []) {
node.src = "index8.html";
}
}
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(document.documentElement, config);
};
test();
</script>
<iframe src="index2.html"></iframe>
</body>
</html>
The MutationObserver interface has successfully detected the addition of an iframe tag in the DOM and manages to "modify" the src attribute. However, the iframe was executed with src=index2.html, not index8.html.
My goal is to place a "hook" when creating an iframe, and to modify the src attribute before the iframe is executed.
Thank you in advance for your help!