My site's scenario is as following:
- When my page loads, it also loads an external Javascript file
- Page's content dynamically change and we don't care, until a certain element appears, for this I do following steps:
- A
MutationObserveris created fordocument - Whenever there are changes, it checks with jQuery if
$("#custom-element").is(":visible") - If that's the case run some customization function and detach the observer
My problem:
- If the page is loaded normally, everything works just fine.
- However my page is designed to be used as an iFrame embed, and when loaded through iFrame the second part of step 4 does not work and
$("#custom-element")returns empty (testing withquerySelectorreturnsnull), even if the element is already there. Inspecting the element in the toolbox seems to "activate" the element, and only after that the custom function is run.
I already had a look at:
- document.querySelector works in console but not on realtime
- document.querySelectorAll returns values only after inspecting DOMs
But the script is loaded in iFrame's <head> tag and both the testing page and the embed page are on the same domain (for testing purposes), so these question do not solve my problem.
My guess is: it has something to do with how MutationObserver is created, but I am not sure.
Here is the observer code part:
const observer = new MutationObserver((mutations, obs) => {
const element = $("#custom-element");
console.log("debug: mutation observer triggered");
if ($(element).is(":visible")) {
console.log("debug: visible");
elementVisibleAction();
obs.disconnect();
return;
}
});
observer.observe(document, {
childList: true,
subtree: true
});
To further clarify it for some readers (as a response to the comments):
- The JS code is inside iFrame and it tries to get an element from inside that same iframe
- The JS code runs fine, if the url of the iFrame is loaded like a normal page
- The iFrame is in viewport and it renders right before my eyes. The
debug: mutation observer triggeredis being print to console - Not only
:visiblereturns false, but the$("#custom-element")is empty, this is the main problem