wait-for-selector

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

Script này sẽ không được không được cài đặt trực tiếp. Nó là một thư viện cho các script khác để bao gồm các chỉ thị meta // @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.

Bạn sẽ cần cài đặt một tiện ích mở rộng như Tampermonkey hoặc Violentmonkey để cài đặt kịch bản này.

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.

(Tôi đã có Trình quản lý tập lệnh người dùng, hãy cài đặt nó!)

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