wait-for-selector

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

Цей скрипт не слід встановлювати безпосередньо. Це - бібліотека для інших скриптів для включення в мета директиву // @require https://update.greasyfork.org/scripts/443087/1038171/wait-for-selector.js

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

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

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

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

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

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

(У мене вже є менеджер скриптів, дайте мені встановити його!)

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.

(I already have a user style manager, let me install it!)

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