Skip to main content
Version: 23.8.0

Page.evaluateHandle() 方法

¥Page.evaluateHandle() method

签名

¥Signature

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

参数

¥Parameters

范围

类型

描述

pageFunction

功能 | 字符串

在页面内运行的函数

args

参数

要传递给 pageFunction 的参数

Returns:

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

备注

¥Remarks

page.evaluatepage.evaluateHandle 之间的唯一区别是 evaluateHandle 将返回封装在页内对象中的值。

¥The only difference between page.evaluate and page.evaluateHandle is that evaluateHandle will return the value wrapped in an in-page object.

如果传递给 page.evaluateHandle 的函数返回 Promise,该函数将等待 Promise 解析并返回其值。

¥If the function passed to page.evaluateHandle returns a Promise, the function will wait for the promise to resolve and return its value.

你可以传递字符串而不是函数(尽管建议使用函数,因为它们更容易调试并与 TypeScript 一起使用):

¥You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):

示例 1

¥Example 1

const aHandle = await page.evaluateHandle('document');

示例 2

¥Example 2

JSHandle 实例可以作为参数传递给 pageFunction

¥JSHandle instances can be passed as arguments to the pageFunction:

const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();

大多数情况下,此函数返回 JSHandle,但如果 pageFunction 返回对元素的引用,则会返回 ElementHandle

¥Most of the time this function returns a JSHandle, but if pageFunction returns a reference to an element, you instead get an ElementHandle back:

示例 3

¥Example 3

const button = await page.evaluateHandle(() =>
document.querySelector('button'),
);
// can call `click` because `button` is an `ElementHandle`
await button.click();

TypeScript 定义假设 evaluateHandle 返回 JSHandle,但如果你知道它将返回 ElementHandle,请将其作为通用参数传递:

¥The TypeScript definitions assume that evaluateHandle returns a JSHandle, but if you know it's going to return an ElementHandle, pass it as the generic argument:

const button = await page.evaluateHandle<ElementHandle>(...);