Page.evaluateOnNewDocument() 方法
🌐 Page.evaluateOnNewDocument() method
添加将在以下场景之一调用的函数:
🌐 Adds a function which would be invoked in one of the following scenarios:
- 每当页面被导航时
- 每当子帧被附加或导航时。在这种情况下,该函数会在新附加的帧的上下文中被调用。
该函数在文档创建后但在其任何脚本运行之前被调用。这对于修改 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
范围 🌐 Parameter | 类型 🌐 Type | 描述 🌐 Description |
|---|---|---|
pageFunction | 函数 | 字符串 🌐 Func | string | 要在浏览器上下文中评估的函数 🌐 Function to be evaluated in browser context |
args | 参数 🌐 Params | 传递给 🌐 Arguments to pass to |
返回:
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);