waitForElement

Waits for an element using the MutationObserver API

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greasyfork.org/scripts/528234/1596455/waitForElement.js

K instalaci tototo skriptu si budete muset nainstalovat rozšíření jako Tampermonkey, Greasemonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat manažer uživatelských skriptů.

(Už mám manažer uživatelských skriptů, nechte mě ho nainstalovat!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Už mám manažer uživatelských stylů, nechte mě ho nainstalovat!)

// ==UserScript==
// @name         waitForElement
// @namespace    Violentmonkey Scripts
// @version      2.0
// @description  Waits for an element using the MutationObserver API
// @author       maanimis
// @grant        none
// ==/UserScript==
 
/**
 * Waits for a element of a given selector.
 *
 * @param {string} selector
 * @returns {Promise<HTMLElement>}
 */
 function waitForElement(selector) {
  return new Promise((resolve) => {
    // Ensure <body> is ready
    function ensureBodyReady(callback) {
      if (document.body) return callback();
      requestAnimationFrame(() => ensureBodyReady(callback));
    }

    ensureBodyReady(() => {
      const ELEMENT = document.querySelector(selector);
      if (ELEMENT) return resolve(ELEMENT);

      console.log("can't find element for selector:", selector, "waiting...");

      const observer = new MutationObserver(() => {
        const ELEMENT = document.querySelector(selector);
        if (ELEMENT) {
          console.log("element found!!");
          resolve(ELEMENT);
          observer.disconnect();
        }
      });

      observer.observe(document.body, {
        childList: true,
        subtree: true,
      });
    });
  });
}