wait-for-selector

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

Ten skrypt nie powinien być instalowany bezpośrednio. Jest to biblioteka dla innych skyptów do włączenia dyrektywą meta // @require https://update.greasyfork.org/scripts/443087/1038171/wait-for-selector.js

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

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

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

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.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

// ==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