首页 > 解决方案 > Javascript:MutationObserver 不显示更改的节点

问题描述

MutationObserver是一个简单的 API,允许我监控 DOM 更改。我在 chrome 扩展中使用它,我想知道何时添加网页上的某些元素。并使用childList应该告诉我指定目标何时添加新节点的选项。

来自 Mozilla 文档:https ://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit/childList

通过将 childList 设置为 true,只要将节点添加到 DOM 节点或从被监视的节点中删除,就会调用您的回调。

但在回调中change.addedNodesandchange.removedNodes是假的。即使打印目标”childNodes.length表明孩子的数量实际上在变化

let content_box = document.querySelector('div#content-box');    // target to monitor

// create observer with callback
let observer = new MutationObserver( (mutations, observer) => {

    mutations.forEach( change => {
            console.log(`Added:  ${change.addedNodes==true}`)    // no added nodes   (there should be)
            console.log(`Removed ${change.removedNodes==true}`)  // no removed nodes (which is fine)
            console.log(change.target)                           // I've confirmed the target is the correct one
            console.log(change.target.childNodes.length)         // after multiple callbacks the length of children is actually increasing 
    })

})


observer.observe(content_box, {
    childList: true,     // monitoring for childList changes
    attributes: false,
    subtree: false,
})

标签: javascriptgoogle-chrome-extension

解决方案


您想检查该属性addedNodes是否在change. 所以console.log("addedNodes" in change)要得到一个真实的结果。

let content_box = document.querySelector('div#content-box');    // target to monitor

// create observer with callback
let observer = new MutationObserver( (mutations, observer) => {

    mutations.forEach( change => {

            console.log(`Added:  ${"addedNodes" in change}`)    // no added nodes   (there should be)

            console.log(`Removed ${"removedNodes" in change}`) // no removed nodes (which is fine)
            console.log(change.target)                           // I've confirmed the target is the correct one
            console.log(change.target.childNodes.length)         // after multiple callbacks the length of children is actually increasing 
    })

})


observer.observe(content_box, {
    childList: true,     // monitoring for childList changes
    attributes: false,
    subtree: false,
})

推荐阅读