waitForElement

Waits for an element using the MutationObserver API

2025/05/26のページです。最新版はこちら

このスクリプトは単体で利用できません。右のようなメタデータを含むスクリプトから、ライブラリとして読み込まれます: // @require https://update.greatest.deepsurf.us/scripts/528234/1596455/waitForElement.js

スクリプトをインストールするには、Tampermonkey, GreasemonkeyViolentmonkey のような拡張機能のインストールが必要です。

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

スクリプトをインストールするには、TampermonkeyViolentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、TampermonkeyUserscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください
// ==UserScript==
// @name         waitForElement
// @namespace    Violentmonkey Scripts
// @version      2.0
// @description  Waits for an element using the MutationObserver API
// @author       maanimis
// @grant        none
// ==/UserScript==
 
/**
 * Waits for a element of a given selector.
 *
 * @param {string} selector
 * @returns {Promise<HTMLElement>}
 */
 function waitForElement(selector) {
  return new Promise((resolve) => {
    // Ensure <body> is ready
    function ensureBodyReady(callback) {
      if (document.body) return callback();
      requestAnimationFrame(() => ensureBodyReady(callback));
    }

    ensureBodyReady(() => {
      const ELEMENT = document.querySelector(selector);
      if (ELEMENT) return resolve(ELEMENT);

      console.log("can't find element for selector:", selector, "waiting...");

      const observer = new MutationObserver(() => {
        const ELEMENT = document.querySelector(selector);
        if (ELEMENT) {
          console.log("element found!!");
          resolve(ELEMENT);
          observer.disconnect();
        }
      });

      observer.observe(document.body, {
        childList: true,
        subtree: true,
      });
    });
  });
}