waitForElement

Waits for an element using the MutationObserver API

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/528234/1701531/waitForElement.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         waitForElement
// @namespace    Violentmonkey Scripts
// @version      3.0
// @description  Waits for an element using the MutationObserver API
// @author       maanimis
// @grant        none
// ==/UserScript==

function waitForElement(selector, timeout = 5000) {
  return new Promise((resolve) => {
    const ELEMENT = document.querySelector(selector);
    if (ELEMENT) {
      return resolve(ELEMENT);
    }
    console.log("[not found] selector: %s\nwaiting...", selector);
    const observer = new MutationObserver(() => {
      const ELEMENT = document.querySelector(selector);
      if (ELEMENT) {
        console.log("element found!!");
        resolve(ELEMENT);
        observer.disconnect();
      }
    });
    if (timeout && timeout >= 0) {
      setTimeout(() => {
        console.log("timeout reached, element not found: %s", selector);
        resolve(null); // Resolve with null if timeout is reached
        observer.disconnect(); // Disconnect the observer if the timeout occurs
      }, timeout);
    }
    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  });
}