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
You cannot pass a function directly into page. evaluate() , but you can call another special method ( page. exposeFunction ), which expose your function as a global function (also available in as an attribute of your page window object), so you can call it when you are inside page.
evaluate() method. Evaluates a function in the page's context and returns the result.
on() . The Puppeteer page class extends Node. js's native EventEmitter , which means that whenever you call page. on() , you are setting up an event listener using Node. js's emitter.
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();
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With