I'm trying to pass a variable into a page.evaluate()
function in Puppeteer, but when I use the following very simplified example, the variable evalVar
is undefined.
I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the page.evaluate()
function so I can use it inside.
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const evalVar = 'WHUT??';
try {
await page.goto('https://www.google.com.au');
await page.waitForSelector('#fbar');
const links = await page.evaluate((evalVar) => {
console.log('evalVar:', evalVar); // appears undefined
const urls = [];
hrefs = document.querySelectorAll('#fbar #fsl a');
hrefs.forEach(function(el) {
urls.push(el.href);
});
return urls;
})
console.log('links:', links);
} catch (err) {
console.log('ERR:', err.message);
} finally {
// browser.close();
}
})();
I have a typescript example that could help someone new in typescript.
Single Variable:
You can pass one variable to
page.evaluate()
using the following syntax:Multiple Variables:
You can pass multiple variables to
page.evaluate()
using the following syntax:You have to pass the variable as an argument to the
pageFunction
like this:The arguments can also be serialized: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args.
For pass a
function
, there are two ways you can do it.You can add
devtools: true
to the launch options for testIt took me quite a while to figure out that
console.log()
inevaluate()
can't show in node console.Ref: https://github.com/GoogleChrome/puppeteer/issues/1944
Hope this can help.
I encourage you to stick on this style, because it's more convenient and readable.