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

如何在Tampermonkey中捕获/监听JavaScript的追加触发事件?

Detecting HTML Appended to in Tampermonkey

Got it, let's break this down. To catch when new HTML gets added to the <body> tag and run your custom function automatically, MutationObserver is exactly the tool you need—it's the standard, performant way to monitor DOM changes without relying on hacky intervals or unnecessary workarounds.

Here's a complete, ready-to-use implementation you can drop into your Tampermonkey script:

// ==UserScript==
// @name         Body Append Detector
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Trigger custom logic when HTML is appended to the page's body
// @author       Your Name
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Replace this with your own custom function
    function handleNewBodyContent(addedNodes) {
        console.log('New HTML was added to the body!', addedNodes);
        // Add your desired logic here—e.g., modify elements, run checks, etc.
    }

    // Set up the MutationObserver to watch for DOM changes
    const bodyObserver = new MutationObserver((mutations) => {
        mutations.forEach(mutation => {
            // Only trigger if actual nodes were added
            if (mutation.addedNodes.length > 0) {
                handleNewBodyContent(mutation.addedNodes);
            }
        });
    });

    // Configure what the observer watches
    const observerSettings = {
        childList: true, // Track direct child nodes being added/removed from body
        subtree: true,   // Optional: Track changes in ALL descendant nodes (not just direct children)
        // Remove `subtree: true` if you only care about elements directly appended to <body>
    };

    // Start observing the body element
    bodyObserver.observe(document.body, observerSettings);

    // Clean up the observer when the page unloads to avoid memory leaks
    window.addEventListener('beforeunload', () => {
        bodyObserver.disconnect();
    });
})();

Quick Tips:

  • No unsafeWindow required: MutationObserver interacts directly with the DOM, which Tampermonkey scripts can access by default (we set @grant none here to keep the environment aligned with the page's context).
  • Tweak the observer settings: If you only need to detect elements added directly as children of <body>, remove the subtree: true line. Keep it enabled if you want to catch HTML added deeper in the DOM tree (like inside a div nested in body).
  • Filter added nodes: The mutation.addedNodes parameter is a NodeList—you can loop through it and check for specific element types, classes, or attributes if you don't want to trigger your function for every single new node.

This method is way more efficient than polling the DOM with setInterval, and it’s supported by all modern browsers.

内容的提问来源于stack exchange,提问作者Faizan Anwer Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:48:08