且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何添加一个事件监听器,触发某个类型的元素被添加到DOM?

更新时间:2023-11-03 17:50:34

您可以使用 MutationObserver 。它可以让你听DOM的突变;它就像你在dom本身设置一个事件监听器,并在每次添加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:

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

这里我们正在收听 document.body ,我们只是监听其子节点的更改(添加或删除节点)。 forEach 遍历每个添加的节点(如果有)并检查它是否为 iFrame 。如果是,那么在do stuff行中做你需要做的事。

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.