インストール
ブラウザで使う
<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/