LoginSignup
1
1

More than 3 years have passed since last update.

ある要素が表示されるまで待つJSライブラリを書いた(MutationObserver)

Last updated at Posted at 2019-08-18

インストール

ブラウザで使う

<script src="https://gistcdn.githack.com/GitHub30/1b13ed6687a22385a81cf98fefdd5a13/raw/42012a345cc5cb1e4f773300e99765b644a40164/async$.js"></script>

Greasemonkey(Tampermonkey)で使う

下記を追加する。

// @require  https://gist.github.com/GitHub30/1b13ed6687a22385a81cf98fefdd5a13/raw/42012a345cc5cb1e4f773300e99765b644a40164/async$.js

使い方

querySelector

const title = await async$('title')
console.log(title.textContent)

Usage

async$(selector, [startNode])

querySelectorAll

const links = await async$$('a')
console.log(links)

Usage

async$$(selector, [startNode])

XPath

const links = await async$x('//a')
console.log(links)

// 要素を1つだけ取得
const h1 = await async$x('//h1', document, XPathResult.FIRST_ORDERED_NODE_TYPE)
console.log(h1.textContent)

Usage

async$x(selector, [startNode], [XPathResult#Constants])

XPathResult#Constants
https://developer.mozilla.org/ja/docs/Web/API/XPathResult#Constants

タイムアウト

// 1秒でタイムアウト
window.ASYNC$_TIMEOUT = 1000
await async$x('//a')

ASYNC$_TIMEOUTにミリ秒でタイムアウトを設定すると、要素が見つからない場合、エラーになります。よしなにtry catchしてください。
デフォルトはタイムアウトしません。

引用

ある要素が表示されるまで待つJSライブラリを書いた(MutationObserver)
https://efcl.info/2015/04/06/wait-for-element/

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1