wait-for-selector

要素がDOMに出現するまで待つユーティリティです。

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/443087/1038171/wait-for-selector.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         wait-for-selector
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @license      MIT
// @description  要素がDOMに出現するまで待つユーティリティです。
// @author       You
// @grant        none
// ==/UserScript==

'use strict'
/**
 * @param {string} selectors
 * @param {number} [timeout=Infinity]
 * @param {ParentNode} [context=document.body]
 * @returns {Promise<Element>}
 */
const waitForSelector = (selectors, timeout = Infinity, context = document.body) => {
  const element = context.querySelector(selectors)

  if (element) {
    return Promise.resolve(element)
  }

  return new Promise((resolve, reject) => {
    const observer = new MutationObserver(records => {
      for (const { addedNodes } of records) {
        if (!addedNodes.length) {
          continue
        }

        const element = context.querySelector(selectors)

        if (!element) {
          continue
        }

        observer.disconnect()
        resolve(element)
      }
    })

    observer.observe(context, {
      childList: true,
      subtree: true
    })

    if (Number.isFinite(timeout)) {
      setTimeout(() => {
        observer.disconnect()
        reject(new Error('Element not found'))
      }, timeout)
    }
  })
}

unsafeWindow.waitForSelector = waitForSelector