如何将所需的模块对象传递给puppeteer page.evaluate

时间:2018-02-15 20:18:09

标签: javascript node.js puppeteer

  • Puppeteer版本:1.0.0
  • 平台/操作系统版本:Windows 10
  • Node.js版本:8.9.3

这是我的代码:

const puppeteer = require('puppeteer');
const varname = require('varname');

...

const page = await browser.newPage();
await page.goto(url);
let generalInfo = await page.evaluate(() => {
        let elements = Array.from(document.querySelectorAll('#order-details > table > tbody > tr'));
        let res = {};
        elements.map((tr) => {
            let split = tr.innerText.trim().split('\t');
            res[varname.camelback(split[0])] = split[1]; // Here is: ... Error: Evaluation failed: ReferenceError: varname is not defined
        });
        return res;
    }); 

...

await browser.close();

显示错误:

  

UnhandledPromiseRejectionWarning:未处理的承诺   rejection(拒绝ID:1):错误:评估失败:ReferenceError:   varname未定义

1 个答案:

答案 0 :(得分:3)

您想在浏览器上下文中使用模块varname。要实现这一点,您应该使用page.addScriptTag()varname注入浏览器,如下所示:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.addScriptTag({ path: './node_modules/varname/build/varname.js' });
    const generalInfo = await page.evaluate(() => {
        return window.varname.camelback('foo_bar_baz');
    });

    console.log(generalInfo); // prints fooBarBaz
    await browser.close();
})();