Greasy Fork

Monkey DOM

Useful library for dealing with the DOM.

目前为 2020-06-21 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.icu/scripts/405802/818776/Monkey%20DOM.js

// ==UserScript==
// @name Monkey DOM
// @namespace https://rafaelgssa.gitlab.io/monkey-scripts
// @author rafaelgssa
// @version 1.0.0
// @description Useful library for dealing with the DOM.
// ==/UserScript==

/**
 * @typedef {(element?: Element) => void} ElementCallback
 * @typedef {(node: Node) => void} NodeCallback
 */

// eslint-disable-next-line
const MonkeyDom = (() => {
	const parser = new DOMParser();

	/**
	 * Waits for an element.
	 * @param {string} selectors The selectors to query for the element.
	 * @param {number} timeout How long to wait for the element in seconds. Defaults to 60 (1 minute).
	 * @returns {Promise<Element | undefined>} The element, if found.
	 */
	const dynamicQuerySelector = (selectors, timeout = 60) => {
		return new Promise((resolve) => _checkElementExists(selectors, resolve, timeout));
	};

	/**
	 * Checks if an element exists, and if not, waits for it.
	 * @param {string} selectors The selectors to query for the element.
	 * @param {ElementCallback} callback The callback to call with the element, if found.
	 * @param {number} timeout How long to wait for the element in seconds. Defaults to 60 (1 minute).
	 */
	const _checkElementExists = (selectors, callback, timeout = 60) => {
		const element = document.querySelector(selectors);
		if (element) {
			callback(element);
		} else if (timeout > 0) {
			window.setTimeout(_checkElementExists, 100, selectors, callback, timeout - 100);
		} else {
			callback();
		}
	};

	/**
	 * Observes a node for mutations.
	 * @param {Node} node The node to observe.
	 * @param {NodeCallback} callback The callback to call with each mutation.
	 * @returns {MutationObserver} The observer.
	 */
	const observeNode = (node, callback) => {
		const observer = new MutationObserver((mutations) =>
			_processNodeMutations(mutations, callback)
		);
		observer.observe(node, {
			attributes: true,
			childList: true,
			subtree: true,
		});
		return observer;
	};

	/**
	 * Processes a node's mutations.
	 * @param {MutationRecord[]} mutations
	 * @param {NodeCallback} callback
	 */
	const _processNodeMutations = (mutations, callback) => {
		for (const mutation of mutations) {
			mutation.addedNodes.forEach(callback);
		}
	};

	/**
	 * Parses an HTML string into a DOM.
	 * @param {string} html The HTML string to parse.
	 * @returns {Document} The parsed DOM.
	 */
	const parse = (html) => {
		return parser.parseFromString(html, 'text/html');
	};

	return {
		dynamicQuerySelector,
		observeNode,
		parse,
	};
})();