Home >Web Front-end >JS Tutorial >How Can I Properly Pass Variables to Puppeteer's `page.evaluate()` Function?

How Can I Properly Pass Variables to Puppeteer's `page.evaluate()` Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 10:20:09671browse

How Can I Properly Pass Variables to Puppeteer's `page.evaluate()` Function?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn