11
  • Puppeteer version: 1.0.0
  • Platform / OS version: Windows 10
  • Node.js version: 8.9.3

Here is my code:

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();

Shows error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: varname is not defined

Alex K
  • 2,613
  • 1
  • 20
  • 31
  • This SO question is relevant: https://stackoverflow.com/questions/53676445/how-to-use-imported-function-inside-page-evaluate-in-puppeteer-with-jest – Motin Aug 10 '21 at 09:29

1 Answers1

13

You want to use module varname in a browser context. To achieve that you should use page.addScriptTag() to inject varname to browser like this:

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();
})();
Everettss
  • 15,475
  • 9
  • 72
  • 98
  • Does it mean that after `evaluate` the `puppeteer` uses its own `window` and other environment? And the jQuery injection does not seem so unnecessary. – contributorpw Jul 24 '18 at 19:24
  • Yes, you can check it by writing console.log(window) inside the eval function and see that it prints out the window object (Node.js has no concept of window) in the browser. – Samir Alajmovic Dec 26 '18 at 14:59
  • @Everettss In production env, node modules won't be available right? as webpack creates a bundle. How we can provide path in production environment? – ni3 Jul 15 '21 at 19:45