Skip to main content
Version: 23.2.0

Page.evaluateOnNewDocument() 方法

¥Page.evaluateOnNewDocument() method

添加将在以下场景之一调用的函数:

¥Adds a function which would be invoked in one of the following scenarios:

  • 每当页面被导航时

    ¥whenever the page is navigated

  • 每当附加或导航子框架时。在这种情况下,该函数在新附加的框架的上下文中调用。

    ¥whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.

在创建文档之后但在运行其任何脚本之前调用该函数。这对于修改 JavaScript 环境很有用,例如 种子 Math.random

¥The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

签名

¥Signature

class Page {
abstract evaluateOnNewDocument<
Params extends unknown[],
Func extends (...args: Params) => unknown = (...args: Params) => unknown,
>(
pageFunction: Func | string,
...args: Params
): Promise<NewDocumentScriptEvaluation>;
}

参数

¥Parameters

范围

类型

描述

pageFunction

功能 | 字符串

要在浏览器上下文中评估的函数

args

参数

要传递给 pageFunction 的参数

Returns:

Promise<NewDocumentScriptEvaluation>

示例

¥Example

在页面加载之前覆盖 navigator.languages 属性的示例:

¥An example of overriding the navigator.languages property before the page loads:

// preload.js

// overwrite the `languages` property to use a custom getter
Object.defineProperty(navigator, 'languages', {
get: function () {
return ['en-US', 'en', 'bn'];
},
});

// In your puppeteer script, assuming the preload.js file is
// in same folder of our script.
const preloadFile = fs.readFileSync('./preload.js', 'utf8');
await page.evaluateOnNewDocument(preloadFile);