有人喜欢词元这个称呼 当然也有人不喜欢,这个脚本会把帖子中的词元修改为token
// ==UserScript==
// @name 去你大爷的词元
// @namespace https://linux.do/
// @version 1.0.0
// @description 在 linux.do 中把“词元”统一替换成 token
// @match https://linux.do/*
// @match http://linux.do/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
const replacements = [
[/词元/g, 'token']
];
// 不处理这些标签里的内容
const ignoredTags = new Set([
'SCRIPT',
'STYLE',
'TEXTAREA',
'INPUT',
'CODE',
'PRE',
'NOSCRIPT'
]);
function replaceTextNode(node) {
if (!node || node.nodeType !== Node.TEXT_NODE) return;
const parent = node.parentElement;
if (!parent || ignoredTags.has(parent.tagName)) return;
let text = node.nodeValue;
let newText = text;
for (const [regex, replacement] of replacements) {
newText = newText.replace(regex, replacement);
}
if (newText !== text) {
node.nodeValue = newText;
}
}
function replaceInElement(root) {
if (!root) return;
if (root.nodeType === Node.TEXT_NODE) {
replaceTextNode(root);
return;
}
if (root.nodeType !== Node.ELEMENT_NODE &&
root.nodeType !== Node.DOCUMENT_NODE &&
root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
return;
}
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT,
{
acceptNode(node) {
const parent = node.parentElement;
if (!parent || ignoredTags.has(parent.tagName)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
let node;
while ((node = walker.nextNode())) {
replaceTextNode(node);
}
}
function start() {
// 先处理当前页面
replaceInElement(document.body);
// 监听 Linux.do 动态加载的新内容
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
// 新增节点
for (const node of mutation.addedNodes) {
replaceInElement(node);
}
// 已有文本发生变化
if (
mutation.type === 'characterData' &&
mutation.target.nodeType === Node.TEXT_NODE
) {
replaceTextNode(mutation.target);
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();