如何在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
unsafeWindowrequired: MutationObserver interacts directly with the DOM, which Tampermonkey scripts can access by default (we set@grant nonehere 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 thesubtree: trueline. 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.addedNodesparameter 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
相关产品推荐
相关产品推荐

