javascript - 是否可以在 nodejs+puppeteer 中包含一个源文件来添加功能?

标签 javascript node.js puppeteer

我知道

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/

相关文章:

javascript - 使用动态过滤器在新窗口中打开 View

node.js - 有没有办法限制我从响应中获取的数据量?

node.js - npm install 和 npm install --save 之间的区别?

Node.js puppeteer - 下载并打开 .idx 文件

javascript - Node js Puppeteer 转到页面数组

javascript - 忽略其中包含特定单词的模式

javascript - 使用 JS 查找字符串中的逗号

javascript - 在导航栏中滚动(Bootstrap 3),但保持页面的其余部分不变

javascript - wait 仅在异步函数的异步函数错误中有效

node.js - puppeteer@5.5.0 安装 : `node install.js` on M1