Mutation Observer - addedNodes[0] 最终变为未定义

Mutation Observer - addedNodes[0] eventually becomes undefined

我正在使用变异观察器从 twitch.tv 中获取任何聊天消息。

var observer = new MutationObserver(function (mutations) {  
    mutations.forEach(function (mutation) {
        if(mutation.addedNodes[0].classList.contains('chat-line__message')){
            counter++;
            console.log(counter);
        }
    });  
}); 

var observerConfig = {        
    childList: true,
};

在聊天达到最大消息量(大约 144 条)之前它工作正常,然后我不断收到:

Uncaught TypeError: Cannot read property 'classList' of undefined

为什么会这样,我该如何克服?

并非每个突变都会添加节点。听起来有些突变只涉及删除的节点。为避免错误,您像往常一样检查是否存在添加的节点:

if(mutation.addedNodes.length && mutation.addedNodes[0].classList.contains('chat-line__message'))

实际上,突变可能会添加多个节点。这是一种更可靠的方法:

mutations.forEach((mutation) => {
  const addedChatLineMessages = Array.from(mutation.addedNodes)
    .filter(({classList}) => classList && classList.contains("chat-line__message"))

  if(addedChatLineMessages.length){
    counter += addedChatLineMessages.length;
    console.log(counter);
  }
});