oban_internet
oban_internet

Reputation: 229

Mutation Observer - addedNodes[0] eventually becomes undefined

I am using a mutation observer to pick up any chat message from 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 :

Uncaught TypeError: Cannot read property 'classList' of undefined

Why is it happening and how can i overcome it?

Upvotes: 1

Views: 1945

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19475

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

Upvotes: 4

Related Questions