You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mutation Observer监听Twitch聊天时addedNodes[0]变为undefined的问题

Fixing "Cannot read property 'classList' of undefined" in Twitch Chat Mutation Observer

Ah, I've run into this exact issue with Twitch's chat UI before! The problem boils down to how Twitch handles old messages once the chat hits that ~144 message limit. Let's break down why your code is failing and how to fix it.

Why the Error Happens

When Twitch's chat reaches its message cap, it doesn't just keep adding new messages—it removes older messages from the DOM at the same time it adds new ones. Your current code assumes that every mutation will always have a addedNodes[0] element, but that's not the case:

  • Sometimes a mutation might only involve removing nodes (no new messages added yet)
  • Even when there are added nodes, the first one in the list might not be a chat message (Twitch adds other UI elements occasionally)
  • When addedNodes is empty, mutation.addedNodes[0] is undefined, hence the TypeError when trying to access classList.

The Fixed Code

Here's a revised version of your observer callback that adds proper checks to avoid the error:

let counter = 0; // Ensure counter is declared (added since it wasn't in your original snippet)
const observer = new MutationObserver(function (mutations) {
  mutations.forEach(function (mutation) {
    // Skip mutations with no added nodes entirely
    if (mutation.addedNodes.length === 0) return;

    // Iterate over ALL added nodes instead of just the first one
    mutation.addedNodes.forEach(node => {
      // Verify the node is an HTML element before checking its class
      if (node instanceof HTMLElement && node.classList.contains('chat-line__message')) {
        counter++;
        console.log(counter);
      }
    });
  });
});

const observerConfig = { childList: true };
// Don't forget to attach the observer to Twitch's chat container!
// observer.observe(document.querySelector('.chat-scrollable-area__message-container'), observerConfig);

Key Improvements

  • Check for empty addedNodes: We skip mutations that don't include new DOM nodes, eliminating the chance of accessing undefined
  • Loop through all added nodes: Twitch might add multiple messages at once, so iterating every node ensures we don't miss any valid chat lines
  • Validate node type: We confirm the node is an HTMLElement before accessing classList—this avoids errors from text nodes or other non-element UI bits that might get added to the chat container

Extra Optimization

If you want to make the chat message check more flexible (in case Twitch updates their class names), you can use the matches() method with a CSS selector instead:

if (node instanceof HTMLElement && node.matches('.chat-line__message')) {
  // ...
}

This works identically but uses a selector syntax that's easier to adjust if Twitch's UI structure changes.

内容的提问来源于stack exchange,提问作者oban_internet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:30