javascriptiframelightbox

capturin an iframe creation even from external source


I am using a third-party SomeScript.js, which is producing an iframe on my page after I click a special button ("special" meaning it has to have a particular id). The process appears simple - "lightbox integration" do they call it - you click the special button, the iframe with mildly sophisticated inputs on a form appears. The problem is, this iframe doesn't have focus. I have found whole articles about how to set a focus on an iframe that you create programmatically in you code. But this isn't the case here. As the 'lightbox' has no focus, it is a bad user experience.

I thought of adding a timeout to the button click, and then search for the newly generated iframe to set the focus, but as I don't control the timing of it's appearance, I wonder if there's some other approach.

Thanks all!


Solution

  • Here is a simple demo, referencing the sample code here: MutationObserver

    const addSomeThing = () => {};
    
    // Copied from MDN demo.
    const whenSomethingHappens = (mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
          console.log('A child node has been added or removed.');
          // This is where we will see our new iFrame.
          
        } else if (mutation.type === 'attributes') {
          console.log(`The ${mutation.attributeName} attribute was modified.`);
        }
      }
    };
    
    document.addEventListener('DOMContentLoaded', () => {
      // Start watching our DOM. 
      const targetNode = document.querySelector("#watchme");
      
      // Mutation Config.
      const config = { attributes: true, childList: true, subtree: true };
      
      // Create an observer instance linked to the callback function
      const observer = new MutationObserver(whenSomethingHappens);
    
      // Start observing the target node for configured mutations
      observer.observe(targetNode, config);
    
     //Lets add something in 5secs. 
     setTimeout(() => { 
      const el = document.createElement('div');
      el.innerHTML = 'Testing';
      document.querySelector('#watchme').appendChild(el);
     }, 5000);
     
    
    });
    <div id="watchme">Here is where we will add</div>