Greasy Fork

来自缓存

UTILS_DOM Library

Eine nützliche Bibliothek für verschiedene Funktionen

目前为 2025-03-01 提交的版本。查看 最新版本

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

// ==UserScript==
// @name         UTILS_DOM Library
// @namespace    dannysaurus.epik
// @version      1.0
// @description  Eine nützliche Bibliothek für verschiedene Funktionen
//
// @license      MIT
// @grant        unsafeWindow
// ==/UserScript==

/* jslint esversion: 11 */
/* global unsafeWindow */
(() => {
    'use strict';
    unsafeWindow.dannysaurus_epik ||= {};
    unsafeWindow.dannysaurus_epik.libraries ||= {};
    unsafeWindow.dannysaurus_epik.libraries.UTILS_DOM = (() => {

        /**
         * Tries to select an element by repeatedly attempting to find it.
         * 
         * @param {Object} options - The options for selecting the element.
         * @param {String} [options.selectors] - The function to select the element.
         * @param {number} [options.maxAttempts=6] - The number of attempts to make.
         * @param {number} [options.intervalMs=10000] - The interval between attempts in milliseconds.
         * @returns {Promise<Element|NodeList>} The selected element(s).
         * 
         * @throws {Error} If the element(s) could not be found.
         */
        const trySelectElement = async ({ selectors, maxAttempts = 6, intervalMs = 10000 } = {}) => {
            const sleep = () => new Promise(resolve => setTimeout(resolve, intervalMs));

            for (let attemptCount = 0; attemptCount < maxAttempts; attemptCount++) {
                const elements = document.querySelector(selectors);
                if (elements instanceof Element || (elements instanceof NodeList && elements.length)) {
                    return elements;
                }
                await sleep();
            }
            throw new Error('Element(s) not found');
        };

        return {
            trySelectElement,
        };
    })();
})();