class: ExecutionContext
该类表示一个 JavaScript 执行的上下文。 [Page] 可能有许多执行上下文:
- 每个 frame 都有 “默认” 的执行上下文,它始终在将帧附加到 DOM 后创建。该上下文由
frame.executionContext()方法返回。 - Extensions 的内容脚本创建了其他执行上下文。
除了页面,执行上下文可以在 workers 中找到。
executionContext.evaluate(pageFunction, …args)
pageFunction<[function]|[string]> Function to be evaluated inexecutionContext...args<…[Serializable]|[JSHandle]> Arguments to pass topageFunction- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of
pageFunction
如果传递给 executionContext.evaluate 的函数返回一个[Promise],那么 executionContext.evaluate 将等待承诺解析并返回它的值。
const executionContext = await page.mainFrame().executionContext();const result = await executionContext.evaluate(() => Promise.resolve(8 * 7));console.log(result); // 输出 "56"
入参可以是一个字符串,但不能是函数。
console.log(await executionContext.evaluate('1 + 2')); // 输出 "3"
[JSHandle] 实例可以作为参数传递给 executionContext.evaluate:
const oneHandle = await executionContext.evaluateHandle(() => 1);const twoHandle = await executionContext.evaluateHandle(() => 2);const result = await executionContext.evaluate((a, b) => a + b, oneHandle, twoHandle);await oneHandle.dispose();await twoHandle.dispose();console.log(result); // 输出 '3'
executionContext.evaluateHandle(pageFunction, …args)
pageFunction<[function]|[string]> 函数在executionContext中被运行...args<…[Serializable]|[JSHandle]> 传递给pageFunction的参数- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of
pageFunctionas in-page object (JSHandle)
executionContext.evaluate 和 executionContext.evaluateHandle 唯一的区别在于executionContext.evaluateHandle 会返回页内对象(JSHandle)。
如果传递给 executionContext.evaluateHandle 的函数返回一个 [Promise],那么executionContext.evaluateHandle将等待承诺解析并返回它的值。
const context = await page.mainFrame().executionContext();const aHandle = await context.evaluateHandle(() => Promise.resolve(self));aHandle; // 处理全局对象
入参可以是一个字符串,但不能是函数。
const aHandle = await context.evaluateHandle('1 + 2'); // 处理'3'对象
[JSHandle] 实例可以作为参数传递给 executionContext.evaluateHandle:
const aHandle = await context.evaluateHandle(() => document.body);const resultHandle = await context.evaluateHandle(body => body.innerHTML, aHandle);console.log(await resultHandle.jsonValue()); // 输出 body 的 innerHTMLawait aHandle.dispose();await resultHandle.dispose();
executionContext.frame()
- returns: <?[Frame]> 与此执行上下文相关的框架。
注意 并非每个执行的上下文都与框架有关系。 例如,workers 和扩展程序具有与框架无关的执行上下文。
executionContext.queryObjects(prototypeHandle)
prototypeHandle<[JSHandle]> 对象原型的句柄- returns: <[JSHandle]> 这个原型的一个对象数组的句柄
该方法重复查找 JavaScript 堆,找到具有给定原型的所有对象。
// 创建一个 Map 对象await page.evaluate(() => window.map = new Map());// 获取 Map 对象原型的句柄const mapPrototype = await page.evaluateHandle(() => Map.prototype);// 将所有映射实例查询到一个数组中const mapInstances = await page.queryObjects(mapPrototype);// 计算堆中映射对象的数量const count = await page.evaluate(maps => maps.length, mapInstances);await mapInstances.dispose();await mapPrototype.dispose();
