Mutation Observer

A simple wrapper around MutationObserver API to watch DOM changes.

À partir de 2024-02-24. Voir la dernière version.

Ce script ne devrait pas être installé directement. C'est une librairie créée pour d'autres scripts. Elle doit être inclus avec la commande // @require https://update.greasyforks.org/scripts/488160/1332701/Mutation%20Observer.js

// ==UserScript==
// @name         Mutation Observer
// @description  A simple wrapper around MutationObserver API to watch DOM changes.
// @version      1.0.2
// @namespace    owowed.moe
// @author       owowed <[email protected]>
// @license      LGPL-3.0
// ==/UserScript==

/**
 * @typedef {MutationObserverInit & {
 *  target: HTMLElement,
 *  abortSignal?: AbortSignal,
 *  once?: boolean
 * }} MakeMutationObserverOptions
 */

/**
 * @typedef {(info: { records: MutationRecord[], observer: MutationObserver }) => void} MakeMutationObserverCallback
 */

/**
 * Create a new `MutationObserver` with options and callback.
 * @param {MakeMutationObserverOptions} options 
 * @param {MakeMutationObserverCallback} callback 
 * @returns {MutationObserver}
 */
function makeMutationObserver({ target, abortSignal, once, ...options }, callback) {
    const observer = new MutationObserver(records => {
        abortSignal?.throwIfAborted();
        if (once) observer.disconnect();
        callback({ records, observer });
    });

    observer.observe(target, options);

    abortSignal?.addEventListener("abort", () => {
        observer.disconnect();
    });

    return observer;
}
长期地址
遇到问题?请前往 GitHub 提 Issues。