How can I add an event listener that triggers whan

2019-07-18 18:37发布

问题:

I want to call a specific method whenever a new iframe is created in the current window . It is youtube iframe player i need to listen to new iframes whenever it is created or enabled in current window . is it possible to do something like that ? Please let me know if there is any way .I have tried the below code but this code wont detect the new iframes which is dynamically created . I tried in google but didn't get any info

const iframes = document.getElementsByTagName('iframe');
  forEach(iframes, (iframe) => {
        addEventListeners(iframe);

      }
    }
  });

回答1:

You can use a MutationObserver. It lets you listen for mutations to the DOM; its like you are setting an event listener on the dom itself, and listening for whenever an iFrame is added to it:

(new MutationObserver(mutations => {
    mutations[0].addedNodes.forEach(node => {
        if (node.tagName.toLowerCase() === 'iframe') {
            //do stuff
        }
    });
})).observe(document.body, {childList: true});

Here we are listening to document.body, and we are only listening for changes to its child nodes (a node is added or deleted). The forEach goes through each added node (if any) and checks if its an iFrame. If it is, then do what you need to do in the "do stuff" line.