Element is not ":visible" if loaded in iFrame

97 views Asked by At

My site's scenario is as following:

  1. When my page loads, it also loads an external Javascript file
  2. Page's content dynamically change and we don't care, until a certain element appears, for this I do following steps:
  3. A MutationObserver is created for document
  4. Whenever there are changes, it checks with jQuery if $("#custom-element").is(":visible")
  5. 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 with querySelector returns null), 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:

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 triggered is being print to console
  • Not only :visible returns false, but the $("#custom-element") is empty, this is the main problem
0

There are 0 answers