我知道
await page.evaluateOnNewDocument(fs.readFileSync('./helperFunctions.js', 'utf8'));
将函数添加到evaluate()
上下文中,这非常方便。
但是有没有人可以提供任何示例以在主要上下文中具有相同的示例?举个例子,说我要加一个
page.existsText()
或
existsText()
使用此代码函数来自要包含/获取的文件:
existsText = (string) => {
// code goes here
}
要走的路是什么?
最佳答案
如果我正确理解了您的意图,您希望将文件中的函数导入全局命名空间,而不必将它们分配给中间变量。这是在 Node 中执行此操作的简单方法。
helperFunctions.js
(function(){
// Assign the function to the scope from where it's called
this.existsText = (string) => {
console.log("Do stuff with " + string);
}
})()
然后当你在 node.js/puppeteer 脚本中需要它时,它会立即执行,将它的函数分配给全局范围:
require("./helperFunctions");
existsText("global scope");
结果:
Do stuff with global scope
好处:在 page.evaluate 中使用相同的函数
如果需要,可以在浏览器范围内使用相同的帮助文件:
await page.evaluateOnNewDocument(fs.readFileSync('./helperFunctions.js', 'utf8'));
await page.evaluate(() => {
existsText("browser scope");
});
Do stuff with browser scope
关于javascript - 是否可以在 nodejs+puppeteer 中包含一个源文件来添加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50485411/