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);
}
}
});
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:Here we are listening to
document.body
, and we are only listening for changes to its child nodes (a node is added or deleted). TheforEach
goes through each added node (if any) and checks if its aniFrame
. If it is, then do what you need to do in the "do stuff" line.