Skip to main content
Version: 23.8.0

Page.waitForFunction() 方法

¥Page.waitForFunction() method

等待提供的函数 pageFunction 在页面上下文中计算时返回真值。

¥Waits for the provided function, pageFunction, to return a truthy value when evaluated in the page's context.

签名

¥Signature

class Page {
waitForFunction<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>,
>(
pageFunction: Func | string,
options?: FrameWaitForFunctionOptions,
...args: Params
): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
}

参数

¥Parameters

范围

类型

描述

pageFunction

功能 | 字符串

将在浏览器上下文中评估函数,直到返回真值。

options

FrameWaitForFunctionOptions

(可选的)用于配置等待行为的选项。

args

参数

Returns:

Promise<HandleFor<Awaited<ReturnType<Func>>>>

示例 1

¥Example 1

Page.waitForFunction() 可用于观察视口大小的变化:

¥Page.waitForFunction() can be used to observe a viewport size change:

import puppeteer from 'puppeteer';
(async () => {
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

¥Example 2

参数可以从 Node.js 传递到 pageFunction

¥Arguments can be passed from Node.js to pageFunction:

const selector = '.foo';
await page.waitForFunction(
selector => !!document.querySelector(selector),
{},
selector,
);

示例 3

¥Example 3

提供的 pageFunction 可以是异步的:

¥The provided pageFunction can be asynchronous:

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,
);