Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

javascript - How to pass required module object to puppeteer page.evaluate

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...