隐藏指定用户(John、Mike及访客)消息的JavaScript代码出现Uncaught TypeError错误的修复咨询
Let's break down what's causing this error and fix it step by step, while making sure your original goal (hiding messages from John, Mike, and guests) works as intended.
The Root Cause
Your error happens when processing the guest's <article> element. For guest messages, there's no <a itemprop="creator"> tag, so e.querySelector('a[itemprop=creator]') returns null. Your original code tries to access e_speaker.innerText even when e_speaker is null, which triggers the TypeError. On top of that, your original logic didn't actually handle hiding guest messages at all—they'd just crash the script instead.
Fixed Code
Here's the revised script that resolves the error and meets all your requirements:
var list_of_blocked = ["john", "mike"]; var style_filter = 'blur(4pt)'; document.querySelectorAll('article').forEach((e) => { // Get the signature element first, add a safety check const signElement = e.querySelector('div.sign'); if (!signElement) return; // Check if this is a guest message const isGuest = signElement.innerText.trim().startsWith('guest'); // Hide guest messages immediately if (isGuest) { e.style.filter = style_filter; return; } // For non-guest messages, get the creator link and add another safety check const speakerElement = e.querySelector('a[itemprop=creator]'); if (!speakerElement) return; const speakerName = speakerElement.innerText.trim(); // Hide messages from blocked users if (list_of_blocked.includes(speakerName)) { e.style.filter = style_filter; } });
Key Improvements
- Defensive checks: We add checks for
signElementandspeakerElementto avoid trying to access properties onnullvalues. - Clearer logic: We separate guest handling from blocked user handling, making the code easier to follow.
- Text trimming: Using
trim()ensures extra spaces in the signature don't break our checks (e.g., " guest " instead of "guest"). - Proper guest handling: Guest messages are now hidden as intended, instead of crashing the script.
内容的提问来源于stack exchange,提问作者john c. j.

