-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutation-observer.js
42 lines (36 loc) · 1.16 KB
/
mutation-observer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// ==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;
}