Greasy Fork

Greasy Fork is available in English.

Twitter特殊词语屏蔽替换

屏蔽或替换Twitter上的特殊词语

目前为 2023-08-21 提交的版本。查看 最新版本

// ==UserScript==
// @name               Twitter特殊词语屏蔽替换
// @name:en            Twitter Special Words Replace
// @name:zh            Twitter特殊词语屏蔽替换
// @namespace          http://greasyfork.icu/zh-CN/users/1155708-dfk-klee
// @version            0.1.1.2
// @description        屏蔽或替换Twitter上的特殊词语
// @description:en     Block or Replace special words on Twitter
// @description:zh     屏蔽或替换Twitter上的特殊词语
// @author             KumaTea DFK_KLEE
// @match              https://twitter.com/*
// @match              https://x.com/*
// @license            GPLv3
// ==/UserScript==

/* jshint esversion: 8 */
// "use strict";
const wordsList = new Map([
  ["8964", "8972"],
  ["8964", "8972"],
  ["八九六四", "八九七二"],
  ["粉蛆", "■■"],
  ["粉红", "■■"],
  ["粉", "■"],
  ["小粉红", "■■■"],
  ["中共", "■■"],
  ["支那", "■■"],
  ["支", "■"],
  ["滞纳", "■■"],
  ["习近平", "■■■"],
  ["xjp", "■■■"],
]);

function replaceStrings(target) {
  const textNodes = target.querySelectorAll("span");
  let replaceCount = 0;
  let existed = false;
  // 使用for of遍历节点
  for (const textNode of textNodes) {
    let newText = textNode.textContent;

    for (const word of wordsList.keys()) {
      const wordReg = new RegExp(word, "gi");
      if (wordReg.test(newText)) {
        existed || (existed = true);
        replaceCount += 1;
        newText = newText.replace(wordReg, wordsList.get(word));
      }
    }

    existed && (textNode.textContent = newText);
  }

  existed &&
    console.log(
      `共屏蔽替换 ${replaceCount} 个词,在 ${textNodes.length} 个节点中`
    );
}

function main() {
  // 监听DOM更新,并执行回调
  const observer = new MutationObserver((mutationsList, observer) => {
    // 获取更新了的节点
    for (const mutation of mutationsList) {
      if (mutation.target) {
        replaceStrings(mutation.target);
      }
    }
  });

  // 监听更新的节点
  observer.observe(document, { childList: true, subtree: true });
}

main();