Passing Variables to Puppeteer's Evaluate Function
In Puppeteer, the page.evaluate() function allows developers to execute JavaScript within the browser context. However, passing variables into this function can be tricky.
Consider the following example:
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(); } })();
In this example, the variable evalVar is undefined within the page.evaluate() function. To resolve this issue, the variable must be passed as an argument to the page function:
const links = await page.evaluate((evalVar) => { console.log(evalVar); // 2. should be defined now ... }, evalVar); // 1. pass variable as an argument
By following this approach, variables can be easily passed into the page.evaluate() function, enabling the execution of more complex operations within the browser context.
The above is the detailed content of How Can I Properly Pass Variables to Puppeteer's `page.evaluate()` Function?. For more information, please follow other related articles on the PHP Chinese website!