該類表示一個 JavaScript 執(zhí)行的上下文。 Page 可能有許多執(zhí)行上下文: 每個 frame 都有 "默認(rèn)" 的執(zhí)行上下文,它始終在將幀附加到 DOM 后創(chuàng)建。該上下文由 frame.executionContext() 方法返回。 Extensions 的內(nèi)容腳本創(chuàng)建了其他執(zhí)行上下文。 除了頁面,執(zhí)行上下文可以在 workers 中找到。
const executionContext = await page.mainFrame().executionContext();
const result = await executionContext.evaluate(() = >Promise.resolve(8 * 7));
console.log(result); // 輸出 "56"
入?yún)⒖梢允且粋€字符串,但不能是函數(shù)。
console.log(await executionContext.evaluate('1 + 2')); // 輸出 "3"
JSHandle 實例可以作為參數(shù)傳遞給 executionContext.evaluate:
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)v0.9.0
executionContext.evaluate 和 executionContext.evaluateHandle 唯一的區(qū)別在于executionContext.evaluateHandle 會返回頁內(nèi)對象(JSHandle)。 如果傳遞給 executionContext.evaluateHandle 的函數(shù)返回一個 Promise,那么executionContext.evaluateHandle將等待承諾解析并返回它的值。
const context = await page.mainFrame().executionContext();
const aHandle = await context.evaluateHandle(() => Promise.resolve(self));aHandle; // 處理全局對象
入?yún)⒖梢允且粋€字符串,但不能是函數(shù)。
const aHandle = await context.evaluateHandle('1 + 2'); // 處理'3'對象
JSHandle 實例可以作為參數(shù)傳遞給
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();
returns: <?Frame> 與此執(zhí)行上下文相關(guān)的框架。
注意 并非每個執(zhí)行的上下文都與框架有關(guān)系。 例如,workers 和擴(kuò)展程序具有與框架無關(guān)的執(zhí)行上下文。
executionContext.queryObjects(prototypeHandle)v0.9.0
// 創(chuàng)建一個 Map 對象
await page.evaluate(() = >window.map = new Map()); // 獲取 Map 對象原型的句柄
const mapPrototype = await page.evaluateHandle(() = >Map.prototype); // 將所有映射實例查詢到一個數(shù)組中
const mapInstances = await page.queryObjects(mapPrototype); // 計算堆中映射對象的數(shù)量
const count = await page.evaluate(maps = >maps.length, mapInstances);
await mapInstances.dispose();
await mapPrototype.dispose();
更多建議: