跳至主要内容

JSHandle

JSHandle代表页面中的一个JavaScript对象。可以通过page.evaluateHandle()方法创建JSHandles。

const windowHandle = await page.evaluateHandle(() => window);
// ...

JSHandle 可以防止引用的 JavaScript 对象被垃圾回收,除非通过 jsHandle.dispose() 显式释放该句柄。当所属的 frame 发生导航或父级上下文被销毁时,JSHandles 会自动释放。

JSHandle实例可以用作page.$eval()page.evaluate()page.evaluateHandle()方法的参数。


方法

asElement

Added before v1.9 jsHandle.asElement

如果对象句柄是ElementHandle的实例,则返回null或对象句柄本身。

用法

jsHandle.asElement();

返回


dispose

Added before v1.9 jsHandle.dispose

jsHandle.dispose 方法停止引用元素句柄。

用法

await jsHandle.dispose();

返回


评估

Added before v1.9 jsHandle.evaluate

返回pageFunction的返回值。

此方法将此句柄作为第一个参数传递给pageFunction

如果 pageFunction 返回一个 Promise,那么 handle.evaluate 将等待该 promise 解析并返回其值。

用法

const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');

参数

返回


evaluateHandle

Added before v1.9 jsHandle.evaluateHandle

pageFunction的返回值作为JSHandle返回。

此方法将此句柄作为第一个参数传递给pageFunction

jsHandle.evaluatejsHandle.evaluateHandle 之间的唯一区别是 jsHandle.evaluateHandle 返回 JSHandle

如果传递给jsHandle.evaluateHandle的函数返回一个Promise,那么jsHandle.evaluateHandle将等待该promise解析并返回其值。

更多详情请参阅page.evaluateHandle()

用法

await jsHandle.evaluateHandle(pageFunction);
await jsHandle.evaluateHandle(pageFunction, arg);

参数

返回


getProperties

Added before v1.9 jsHandle.getProperties

该方法返回一个映射,其中自有属性名作为键,属性值对应的JSHandle实例作为值。

用法

const handle = await page.evaluateHandle(() => ({ window, document }));
const properties = await handle.getProperties();
const windowHandle = properties.get('window');
const documentHandle = properties.get('document');
await handle.dispose();

返回


getProperty

Added before v1.9 jsHandle.getProperty

从引用的对象中获取单个属性。

用法

await jsHandle.getProperty(propertyName);

参数

  • propertyName string#

    要获取的属性

返回


jsonValue

Added before v1.9 jsHandle.jsonValue

返回该对象的JSON表示形式。如果对象具有toJSON函数,它将不会被调用

note

如果引用的对象无法字符串化,该方法将返回一个空的JSON对象。如果对象存在循环引用,则会抛出错误。

用法

await jsHandle.jsonValue();

返回