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

隐藏指定用户(John、Mike及访客)消息的JavaScript代码出现Uncaught TypeError错误的修复咨询

Fixing the "Cannot read property 'innerText' of null" Error in Your Message-Hiding Script

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 signElement and speakerElement to avoid trying to access properties on null values.
  • 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.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:34:07