使用Mutation Observer监听Twitch聊天时addedNodes[0]变为undefined的问题
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
addedNodesis empty,mutation.addedNodes[0]isundefined, hence the TypeError when trying to accessclassList.
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
HTMLElementbefore accessingclassList—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

