class: JSHandle
JSHandle表示页内JavaScript对象。可以使用page.evaluateHandle方法创建JSHandles。
const windowHandle = await page.evaluateHandle(() => window);
// ...
除非处理是disposed,否则 JSHandle 防止对引用的 JavaScript 对象进行垃圾回收。当其原始 frame 被导航或父上下文被销毁时,JSHandles 被自动处置。
JSHandle 实例可用作page。$ eval()
,page.evaluate()
和page.evaluateHandle
方法的参数。
jsHandle.asElement()
- returns: <?[ElementHandle]
如果对象句柄是[ElementHandle]的实例,则返回null
或对象句柄本身。
jsHandle.dispose()
- returns: <[Promise]> 成功解决对象句柄时解析的 Promise 。
jsHandle.dispose
方法停止引用元素句柄。
jsHandle.evaluate(pageFunction[, ...args])
pageFunction
<[function]([Object])> 在浏览器上下文中要运行的函数。...args
<...[Serializable]|[JSHandle]> 传递给pageFunction
的参数。- returns: <[Promise]<[Serializable]>>
pageFunction
的返回值为Promise。
此方法将此句柄作为第一个参数传递给pageFunction
。
如果pageFunction
返回一个[Promise],则handle.evaluate
将等待 promise 并返回其值。
例:
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
jsHandle.evaluateHandle(pageFunction[, ...args])
pageFunction
<[function]|[string]> 要运行的函数。...args
<...[Serializable]|[JSHandle]> 传递给pageFunction
的参数。- returns: <[Promise]<[JSHandle]>>
pageFunction
的返回值 Promise 解析为页内对象(JSHandle) 。
此方法将此句柄作为第一个参数传递给pageFunction
。
jsHandle.evaluate
和jsHandle.evaluateHandle
之间的唯一区别是executionContext.evaluateHandle
返回页内对象(JSHandle)。
如果传递给jsHandle.evaluateHandle
的函数返回[Promise],则jsHandle.evaluateHandle
将等待 promise 处理并返回其值。
有关更多详细信息,请参见Page.evaluateHandle。
jsHandle.executionContext()
- returns: <[ExecutionContext]>
返回句柄所属的执行上下文。
jsHandle.getProperties()
- returns: <[Promise]<[Map]<[string], [JSHandle]>>>
该方法返回一个 map ,该 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)
propertyName
<[string]> 要获取的属性名称- returns: <[Promise]<[JSHandle]>>
从引用的对象中获取单个属性。
jsHandle.jsonValue()
- returns: <[Promise]<[Object]>>
返回 JSON 形式的对象。如果对象有toJSON
方法,它不会被调用。
注意 如果引用的对象不可字符串化,则该方法将返回一个空的 JSON 对象。如果对象具有循环引用,将引发错误。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。