为什么这个 MutationObserver 没有观察到任何突变?

why is this MutationObserver not observing any mutations?

我在 Firefox 的 GreaseMonkey 脚本中执行此操作。我正在尝试通过 Ajax 检测添加的新子 div,我想,这个页面不是我自己的。它是一个类似于 Discord 或 Slack 的 chat/collaboration 应用程序。我从 MDN 上的 MutationObserver 文档中复制了这个模式。这是相关位:

function findNewMessages() {
  console.log("findNewMessages");
  
  // Select the node that will be observed for mutations
  const targetNode = document.getElementsByClassName("scrollerInner-2YIMLh");
  if(targetNode) {
        console.log("findNewMessages::found scrollerInner");
  }
  
  // Options for the observer (which mutations to observe)
    const config = { childList: true, subtree: true };
  
  // Callback function to execute when mutations are observed
  const callback = function(mutationsList, observer) {
      
      for(const mutation of mutationsList) {
          if (mutation.type === 'childList') {
              console.log('findNewMessages:: A child node has been added or removed.');
          }
          else {
            console.log("findNewMessages:: mutation : " + JSON.stringify(mutation));
          }
      }
  };

  // Create an observer instance linked to the callback function
  const observer = new MutationObserver(callback);
  
  // Start observing the target node for configured mutations
  observer.observe(targetNode, config);

  // Later, you can stop observing
//   observer.disconnect();
}

// delay for page to load; 
// tried @run-at      document-idle in the header but it wasn't working
setTimeout(findNewMessages, 10000);

正在找到目标节点,它是正确的。我输入了一条消息并观察到添加了一个新的子元素,但是突变观察器没有触发。

根据这里的问题,我找到了另一种我试过的表格:

var observer = new MutationObserver(function(mutations) {
    for(const mutation of mutationsList) {
      if (mutation.type === 'childList') {
        console.log('findNewMessages:: A child node has been added or removed.');
      }
      else {
        console.log("findNewMessages:: mutation : " + JSON.stringify(mutation));
      }
    }
  });

相同的结果,没有突变。
我也尝试使用在另一个答案中找到的 MutationSummary library,但遇到了同样的问题。我的 javascript 和选择器语法很生疏;我遗漏了什么明显的东西吗?

document.getElementsByClassName("scrollerInner-2YIMLh");

returnshtml元素集合

observer.observe() 的第一个参数接受特定元素而不是集合。 所以你必须使用 getElementById.

否则您可以使用 for 循环来迭代您的 targetNode 变量。