简体   繁体   English

突变观察者-addedNodes [0]最终变得不确定

[英]Mutation Observer - addedNodes[0] eventually becomes undefined

I am using a mutation observer to pick up any chat message from twitch.tv. 我正在使用变异观察者从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,
};

It works fine up until chat reaches maximum amount of messages which is about about 144 and then i keep getting : 它可以正常工作,直到聊天达到大约144条消息的最大数量,然后我不断得到:

Uncaught TypeError: Cannot read property 'classList' of undefined

Why is it happening and how can i overcome it? 为什么会发生这种情况,我该如何克服呢?

Not every mutation adds nodes. 并非每个突变都添加节点。 It sounds like some mutations involve only removed nodes. 听起来有些突变仅涉及已删除的节点。 To avoid the error, you check for the existence of added nodes, as usual: 为避免该错误,请照常检查是否存在添加的节点:

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

Actually, mutations may add multiple nodes. 实际上,变异可能会添加多个节点。 This is a more robust approach: 这是一种更可靠的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM