Skip to main content

JSHandle

JSHandle 表示页面内的 JavaScript 对象。JSHandles 可以使用 page.evaluateHandle(pageFunction[, arg]) 方法创建。

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

JSHandle 防止引用的 JavaScript 对象被垃圾回收,除非使用 jsHandle.dispose() 释放句柄。当 JSHandles 的源 frame 导航或父上下文被销毁时,JSHandles 会自动释放。

JSHandle 实例可用作 page.$eval(selector, pageFunction[, arg, options])page.evaluate(pageFunction[, arg])page.evaluateHandle(pageFunction[, arg]) 方法中的参数。

jsHandle.asElement()

Added in: v1.8

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

jsHandle.dispose()

Added in: v1.8

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

jsHandle.evaluate(pageFunction[, arg])

Added in: v1.8

返回 pageFunction 的返回值。

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

如果 pageFunction 返回 Promise,则 handle.evaluate 将等待 promise 解析并返回其值。

Examples:

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

jsHandle.evaluateHandle(pageFunction[, arg])

Added in: v1.8

JSHandle 形式返回 pageFunction 的返回值。

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

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

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

有关详细信息,请参阅 page.evaluateHandle(pageFunction[, arg])

jsHandle.getProperties()

Added in: v1.8

该方法返回一个 map,其中包含作为键的 自身属性名称 和作为属性值的 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();

jsHandle.getProperty(propertyName)

Added in: v1.8

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

jsHandle.jsonValue()

Added in: v1.8

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

note

如果引用的对象不可字符串化,则该方法将返回一个空的 JSON 对象。如果对象具有循环引用,它将抛出错误。