跳到正文

个人记录

冰冰冰

Slimu约 21 分钟
原文
文章信息与版本

文章信息

发布
2026年10月7日
收录
2026年10月9日
更新
2026年11月17日
篇幅
约 21 分钟

版本

  1. v1当前

本插件为娱乐向,使用本🧊(插)件可能🧊(会)致编辑文本🧊🧊(时体)验不良,实用性可能较小甚至为负。

介绍

本插件实现的功能是将聚焦的编辑框内的字符随机替换为指定字符串,匹配指定字符串并保证不替换其中内容。

替换速度从聚焦编辑框后的第 3 秒🧊始逐步增加,最大为每秒替换两个字符。

指定字符串、开始🧊(时)间、最大🧊(速)度、增长🧊(到)最大速度的时间均可设置。

欢迎大家改进代码!

代码

代码使用 DeepSeek V4.1 Flash 生成。

请安装篡改猴使用。

JavaScript
// ==UserScript==
// @name         输入框字符随机替换(速度渐增·退出重置)
// @namespace    https://github.com/yourname/typing-chaos
// @version      1.2.0
// @description  检测当前聚焦的输入框,从第 3 秒起以「由 0 逐渐增大」的速度,随机把一个字符替换成用户指定的字符串;已被替换的字符串不会再被替换;退出编辑时速度重置
// @author       You
// @match        *://*/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// ==/UserScript==

(function () {
  'use strict';

  /* ================= 默认配置 ================= */
  const DEFAULTS = {
    enabled:         true,
    replaceWith:     '🧊',
    startDelay:      3000,   // ms:第 3 秒才开始动手
    rampTime:        100000,   // ms:速度从 0 涨到最大值所需时间
    maxRate:         2,      // 次/秒:最大替换频率
    minLength:       1,
    includePassword: false,
  };

  const cfg = {
    enabled:         GM_getValue('enabled',         DEFAULTS.enabled),
    replaceWith:     GM_getValue('replaceWith',     DEFAULTS.replaceWith),
    startDelay:      GM_getValue('startDelay',      DEFAULTS.startDelay),
    rampTime:        GM_getValue('rampTime',        DEFAULTS.rampTime),
    maxRate:         GM_getValue('maxRate',         DEFAULTS.maxRate),
    minLength:       GM_getValue('minLength',       DEFAULTS.minLength),
    includePassword: GM_getValue('includePassword', DEFAULTS.includePassword),
  };

  function save(key, value) {
    cfg[key] = value;
    GM_setValue(key, value);
  }

  /* ================= 运行时状态 ================= */
  let target     = null;
  let clockStart = 0;         // 0 = 未开始计时
  let acc        = 0;
  let lastFrame  = performance.now();

  /* ================= 重置计时器 ================= */
  function resetTimer() {
    clockStart = 0;
    acc = 0;
  }

  /* ================= 小提示 ================= */
  function toast(msg) {
    const d = document.createElement('div');
    d.textContent = msg;
    d.style.cssText =
      'position:fixed;z-index:2147483647;left:50%;top:24px;transform:translateX(-50%);' +
      'background:rgba(20,20,20,.9);color:#fff;font:13px/1.6 -apple-system,"Segoe UI",sans-serif;' +
      'padding:8px 14px;border-radius:8px;pointer-events:none;opacity:0;transition:opacity .2s;';
    document.documentElement.appendChild(d);
    requestAnimationFrame(() => { d.style.opacity = '1'; });
    setTimeout(() => {
      d.style.opacity = '0';
      setTimeout(() => d.remove(), 300);
    }, 1400);
  }

  /* ================= 判断是否可编辑 ================= */
  const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password']);

  function isEditable(el) {
    if (!el || el.nodeType !== 1) return false;
    if (el.isContentEditable) return true;

    const tag = el.tagName;
    if (tag === 'TEXTAREA') return !el.disabled && !el.readOnly;
    if (tag === 'INPUT') {
      const type = (el.getAttribute('type') || 'text').toLowerCase();
      if (!TEXT_INPUT_TYPES.has(type)) return false;
      if (type === 'password' && !cfg.includePassword) return false;
      return !el.disabled && !el.readOnly;
    }
    return false;
  }

  /* ================= 计算“受保护”的索引 ================= */
  function getProtectedIndices(text, rep) {
    const set = new Set();
    if (!rep || !text) return set;

    let from = 0;
    while (true) {
      const i = text.indexOf(rep, from);
      if (i === -1) break;
      for (let k = 0; k < rep.length; k++) set.add(i + k);
      from = i + rep.length;
    }
    return set;
  }

  /* ================= 用原生 setter 写值 ================= */
  function setNativeValue(el, value) {
    const proto = el instanceof HTMLTextAreaElement
      ? HTMLTextAreaElement.prototype
      : HTMLInputElement.prototype;

    const desc = Object.getOwnPropertyDescriptor(proto, 'value');
    if (desc && desc.set) desc.set.call(el, value);
    else el.value = value;

    el.dispatchEvent(new Event('input', { bubbles: true }));
  }

  /* ================= contenteditable 处理 ================= */
  function replaceInContentEditable(el, rep) {
    const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null);
    const nodes = [];
    let n;
    while ((n = walker.nextNode())) {
      if (n.nodeValue && n.nodeValue.length) nodes.push(n);
    }

    let fullText = '';
    const positions = [];
    for (const node of nodes) {
      const s = node.nodeValue;
      for (let i = 0; i < s.length; i++) positions.push({ node, offset: i });
      fullText += s;
    }
    if (fullText.length < cfg.minLength) return false;

    const protectedSet = getProtectedIndices(fullText, rep);
    const candidates = [];
    for (let i = 0; i < fullText.length; i++) {
      if (!protectedSet.has(i)) candidates.push(i);
    }
    if (candidates.length === 0) return false;

    const idx = candidates[Math.floor(Math.random() * candidates.length)];
    const { node, offset } = positions[idx];

    const v = node.nodeValue;
    node.nodeValue = v.slice(0, offset) + rep + v.slice(offset + 1);

    try {
      el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: rep }));
    } catch (_) {
      el.dispatchEvent(new Event('input', { bubbles: true }));
    }
    return true;
  }

  /* ================= 核心:随机替换一个字符 ================= */
  function doReplace() {
    const el = target;
    if (!el || !el.isConnected) return false;
    if (document.activeElement !== el) return false;
    if (!el.isContentEditable && (el.disabled || el.readOnly)) return false;

    const rep = cfg.replaceWith;
    if (!rep) return false;

    if (el.isContentEditable) {
      return replaceInContentEditable(el, rep);
    }

    const value = el.value || '';
    if (value.length < cfg.minLength) return false;

    const protectedSet = getProtectedIndices(value, rep);
    const candidates = [];
    for (let i = 0; i < value.length; i++) {
      if (!protectedSet.has(i)) candidates.push(i);
    }
    if (candidates.length === 0) return false;

    const idx = candidates[Math.floor(Math.random() * candidates.length)];

    const selStart = el.selectionStart;
    const selEnd   = el.selectionEnd;

    const newValue = value.slice(0, idx) + rep + value.slice(idx + 1);
    setNativeValue(el, newValue);

    const delta = rep.length - 1;
    if (selStart != null && selEnd != null) {
      try {
        el.setSelectionRange(
          selStart > idx ? selStart + delta : selStart,
          selEnd   > idx ? selEnd   + delta : selEnd
        );
      } catch (_) { /* 某些 input type 不支持,忽略 */ }
    }

    return true;
  }

  /* ================= 主循环:速度由 0 逐渐增大 ================= */
  function frame(now) {
    const dt = Math.min((now - lastFrame) / 1000, 0.25);
    lastFrame = now;

    if (!cfg.enabled || !target || !clockStart) {
      acc = 0;
      requestAnimationFrame(frame);
      return;
    }

    const elapsed = now - clockStart;

    // 前 3 秒:速度为 0
    if (elapsed < cfg.startDelay) {
      acc = 0;
      requestAnimationFrame(frame);
      return;
    }

    const p = cfg.rampTime > 0
      ? Math.min((elapsed - cfg.startDelay) / cfg.rampTime, 1)
      : 1;

    const rate = cfg.maxRate * p;

    acc += rate * dt;
    while (acc >= 1) {
      acc -= 1;
      if (!doReplace()) { acc = 0; break; }
    }

    requestAnimationFrame(frame);
  }

  /* ================= 焦点跟踪 ================= */
  document.addEventListener('focusin', (e) => {
    const el = e.target;
    if (isEditable(el)) {
      target = el;
      // 每次(重新)进入编辑:从头开始计时
      // 如果同一个元素再次 focusin(比如点击回同一个输入框),也重置
      clockStart = performance.now();
      acc = 0;
    } else {
      target = null;
      resetTimer();
    }
  }, true);

  document.addEventListener('focusout', () => {
    // 退出编辑:立刻停手,并清零计时器与累加器
    resetTimer();
    target = null;

    // 万一同一次焦点切换里马上又 focus 到别处,focusin 会接手重新计时;
    // 这里再用 rAF 兜底确认一次(防止 activeElement 仍可编辑但没触发 focusin 的边缘情况)
    requestAnimationFrame(() => {
      const a = document.activeElement;
      if (isEditable(a)) {
        target = a;
        // 只有在目标发生改变、或 clockStart 仍为 0 时才重新计时
        if (a !== target || !clockStart) {
          clockStart = performance.now();
          acc = 0;
        }
      } else {
        target = null;
        resetTimer();
      }
    });
  }, true);

  // 页面加载时若已有焦点元素,正常初始化
  if (isEditable(document.activeElement)) {
    target = document.activeElement;
    clockStart = performance.now();
  }

  requestAnimationFrame(frame);

  /* ================= 菜单命令 ================= */
  GM_registerMenuCommand(`${cfg.enabled ? '🟢' : '🔴'} 启用 / 停用`, () => {
    save('enabled', !cfg.enabled);
    toast(cfg.enabled ? '已启用' : '已停用');
  });

  GM_registerMenuCommand('✏️ 设置替换字符串', () => {
    const v = prompt('要把字符替换成什么?', cfg.replaceWith);
    if (v !== null && v !== '') {
      save('replaceWith', v);
      toast('替换字符串已设为:' + v);
    }
  });

  GM_registerMenuCommand('⏱️ 设置开始延迟(毫秒)', () => {
    const v = prompt('第几毫秒开始替换?(默认 3000)', String(cfg.startDelay));
    const n = Number(v);
    if (Number.isFinite(n) && n >= 0) { save('startDelay', n); toast('开始延迟:' + n + ' ms'); }
  });

  GM_registerMenuCommand('📈 设置加速时长(毫秒)', () => {
    const v = prompt('速度从 0 涨到最大值需要多久?(默认 8000)', String(cfg.rampTime));
    const n = Number(v);
    if (Number.isFinite(n) && n > 0) { save('rampTime', n); toast('加速时长:' + n + ' ms'); }
  });

  GM_registerMenuCommand('🚀 设置最大速度(次/秒)', () => {
    const v = prompt('最大替换频率(默认 5 次/秒)', String(cfg.maxRate));
    const n = Number(v);
    if (Number.isFinite(n) && n > 0) { save('maxRate', n); toast('最大速度:' + n + ' 次/秒'); }
  });

  GM_registerMenuCommand('🔢 设置最小字符数', () => {
    const v = prompt('输入框至少要有几个字符才开始替换?(默认 1)', String(cfg.minLength));
    const n = Number(v);
    if (Number.isFinite(n) && n >= 1) { save('minLength', n); toast('最小字符数:' + n); }
  });

  GM_registerMenuCommand('🔁 重置计时器(重新从第 3 秒开始)', () => {
    clockStart = performance.now();
    acc = 0;
    toast('计时器已重置');
  });

  GM_registerMenuCommand('♻️ 恢复默认设置', () => {
    if (!confirm('确定恢复全部默认设置?')) return;
    Object.keys(DEFAULTS).forEach((k) => save(k, DEFAULTS[k]));
    toast('已恢复默认设置');
  });

})();

🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊🧊

原文