Page.waitForFunction() 方法
等待所提供的函数 pageFunction 在页面上下文中求值时返回真值。
签名
class Page {
waitForFunction<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>,
>(
pageFunction: Func | string,
options?: FrameWaitForFunctionOptions,
...args: Params
): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
}
参数
|
参数 |
类型 |
说明 |
|---|---|---|
|
pageFunction |
Func | string |
要在浏览器上下文中求值的函数,直到其返回真值。 |
|
options |
(可选) 用于配置等待行为的选项。 | |
|
args |
Params |
返回值:
Promise<HandleFor<Awaited<ReturnType<Func>>>>
示例 1
Page.waitForFunction() 可用于观察视口大小的变化:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
const watchDog = page.waitForFunction('window.innerWidth < 100');
await page.setViewport({width: 50, height: 50});
await watchDog;
await browser.close();
示例 2
可以从 Node.js 向 pageFunction 传递参数:
const selector = '.foo';
await page.waitForFunction(
selector => !!document.querySelector(selector),
{},
selector,
);
示例 3
所提供的 pageFunction 可以是异步的:
const username = 'github-username';
await page.waitForFunction(
async username => {
const githubResponse = await fetch(
`https://api.github.com/users/${username}`,
);
const githubUser = await githubResponse.json();
// show the avatar
const img = document.createElement('img');
img.src = githubUser.avatar_url;
// wait 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
},
{},
username,
);