JSHandle
JSHandle 表示页面中的一个 JavaScript 对象。可以通过 page.evaluateHandle() 方法创建 JSHandle 实例。
const windowHandle = await page.evaluateHandle(() => window);
// ...
JSHandle 可以防止引用的 JavaScript 对象被垃圾回收,除非通过 jsHandle.dispose() 方法显式释放。当所属的 frame 发生导航或父级上下文被销毁时,JSHandle 会自动释放。
JSHandle 实例可以作为参数传递给 page.$eval()、page.evaluate() 和 page.evaluateHandle() 方法。
方法
asElement
v1.9 之前添加如果对象句柄是 ElementHandle 的实例,则返回该对象句柄本身,否则返回 null
。
用法
jsHandle.asElement();
返回值
dispose
v1.9 之前添加jsHandle.dispose
方法停止对该元素句柄的引用。
用法
await jsHandle.dispose();
返回值
evaluate
v1.9 版本前添加返回 pageFunction 的执行结果。
该方法会将当前句柄作为第一个参数传递给 pageFunction。
如果 pageFunction 返回一个 Promise,则 handle.evaluate
会等待该 Promise 解析并返回其值。
用法
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
参数
-
pageFunction
function | string#需要在页面上下文中执行的函数。
-
arg
EvaluationArgument (可选)#传递给 pageFunction 的可选参数。
返回值
evaluateHandle
v1.9 版本前添加将 pageFunction 的返回值作为 JSHandle 返回。
此方法会将当前句柄作为第一个参数传递给 pageFunction。
jsHandle.evaluate
和 jsHandle.evaluateHandle
的唯一区别在于 jsHandle.evaluateHandle
返回的是 JSHandle。
如果传递给 jsHandle.evaluateHandle
的函数返回一个 Promise,则 jsHandle.evaluateHandle
会等待该 Promise 解析并返回其值。
更多详情请参阅 page.evaluateHandle()。
用法
await jsHandle.evaluateHandle(pageFunction);
await jsHandle.evaluateHandle(pageFunction, arg);
参数
-
pageFunction
function | string#要在页面上下文中执行的函数。
-
arg
EvaluationArgument (可选)#传递给 pageFunction 的可选参数。
返回值
getProperties
Added before v1.9该方法返回一个映射(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();
返回值
getProperty
Added before v1.9从引用对象中获取单个属性。
用法
await jsHandle.getProperty(propertyName);
参数
返回值
jsonValue
v1.9 版本前添加返回对象的 JSON 表示形式。如果对象有 toJSON
方法,该方法不会被调用。
如果引用的对象不可字符串化,该方法将返回一个空的 JSON 对象。如果对象存在循环引用,则会抛出错误。
用法
await jsHandle.jsonValue();
返回值