miao

· · 个人记录


// ==UserScript==
// @name         喵喵喵
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  所有网页文本标点前自动随机添加:喵
// @author       original: 洛谷 fkxr & p91s2964
// @match        *://*/*
// @grant        none
// ==/UserScript==
(function () {
    'use strict';

    // 猫娘词语库,可以自己增删
    const wordList = ['喵', '喵呜'];
    function getRandomWord() {
        return wordList[Math.floor(Math.random() * wordList.length)];
    }

    const targetRegex = /([,。!?;:])/g;
    let watchedNodes = new WeakSet();

    function miaoTransform(root) {
        const walker = document.createTreeWalker(
            root,
            NodeFilter.SHOW_TEXT,
            {
                acceptNode: node => {
                    const p = node.parentElement;
                    if (!p) return NodeFilter.FILTER_REJECT;
                    const tag = p.tagName;
                    // 不处理这些标签,防止输入框、代码乱掉
                    if (['SCRIPT', 'STYLE', 'TEXTAREA', 'INPUT', 'CODE', 'PRE'].includes(tag))
                        return NodeFilter.FILTER_REJECT;
                    return NodeFilter.FILTER_ACCEPT;
                }
            }
        );

        let node;
        while ((node = walker.nextNode())) {
            if (watchedNodes.has(node)) continue;
            const txt = node.textContent;
            if (!targetRegex.test(txt)) continue;

            watchedNodes.add(node);
            // 替换:随机词语 + 空格 + 标点
            const newTxt = txt.replace(targetRegex, (match, p1) => {
                return `${getRandomWord()} ${p1}`;
            });
            node.textContent = newTxt;
        }
    }

    // MutationObserver:去掉 characterData,防止无限递归修改文字
    const observer = new MutationObserver(muts => {
        for (const m of muts) {
            miaoTransform(m.target);
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // 页面初始加载执行一次
    miaoTransform(document.body);
})();