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

问题描述

我在 Firefox 中的 GreaseMonkey 脚本中执行此操作。我正在尝试通过 Ajax 检测添加的新子 div,我想,这个页面不是我自己的。这是一个聊天/协作应用程序,如 discord 或 Slack。我从 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);

targetNode 正在被找到并且是正确的。我输入了一条消息并看到添加一个新的子元素,但变异观察器没有触发。

基于这里的问题,我找到了另一种我尝试过的形式:

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");

返回元素的 html 集合

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

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