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

如何在指定元素出现特定文本时触发函数?Greasemonkey场景实现

Greasemonkey 监听指定元素内容变动实现自动插入节点脚本

实现思路

使用MutationObserverAPI监听目标元素的内容变化,匹配到指定文本后自动插入你需要的节点即可,不需要额外依赖。

完整脚本代码

// ==UserScript==
// @name         监听特定文本插入自定义节点
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  当#someid元素内出现指定文本时插入自定义div
// @author       Scorpys
// @match        *://你需要生效的网站域名/* // 把这里替换成你实际要运行脚本的网站地址
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // 先获取目标元素
    const targetNode = document.getElementById('someid');
    if (!targetNode) return;

    // 配置观察者要监听的变动类型
    const observerConfig = {
        childList: true,
        subtree: true,
        characterData: true
    };

    // 观察者回调函数
    const observerCallback = (mutationsList, observer) => {
        // 检查当前目标元素内容是否包含指定文本
        if (targetNode.textContent.includes('Some text here...')) {
            // 创建要插入的节点
            const insertDiv = document.createElement('div');
            insertDiv.id = 'idbla';
            insertDiv.textContent = 'This is text...';
            // 不需要可见的话可以加下面这行,不影响HTML结构存在
            // insertDiv.style.display = 'none';
            // 插入到body末尾,也可以换成其他父节点
            document.body.appendChild(insertDiv);
            // 只需要触发一次的话就停止监听,不需要重复触发可以删掉这行
            observer.disconnect();
        }
    };

    // 启动观察者
    const observer = new MutationObserver(observerCallback);
    observer.observe(targetNode, observerConfig);
})();

注意事项

  • 脚本头的@match字段需要替换为你要生效的实际网站地址,支持通配符
  • 如果你不需要插入的div在页面可见,可以放开注释里的display: none配置,不会影响该节点在HTML结构中的存在
  • 监听配置默认会检查元素下所有子节点的内容变化,哪怕目标文本是嵌套在子元素内也能正常识别
  • 默认只触发一次插入操作,如果需要每次出现指定文本都重复操作,删掉observer.disconnect()即可

内容的提问来源于stack exchange,提问作者Scorpys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:24:05