make-mutation-observer

A simple wrapper around MutationObserver API to watch DOM changes.

目前為 2024-02-24 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/488160/1332706/make-mutation-observer.js

// ==UserScript==
// @name         make-mutation-observer
// @description  A simple wrapper around MutationObserver API to watch DOM changes.
// @version      0.0.1
// @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;
}