Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading