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

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

Linda Hamilton
Release: 2024-12-16 08:30:15
Original
880 people have browsed it

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

How to Pass Variables into an Evaluate Function in Puppeteer

When using Puppeteer to evaluate a page, it's often necessary to pass variables into the evaluation function for use within the page's context. To achieve this, it's essential to understand the correct method of passing variables into the page.evaluate() function.

In the provided Puppeteer script, attempts to pass the variable evalVar into the evaluation function links are unsuccessful, resulting in the variable being undefined when accessed within the function. This occurs because variables cannot be passed directly into the function.

The solution lies in passing variables as arguments to the evaluation function. By adding the following changes to the links function, the variable evalVar will be passed and accessible within the function:

const links = await page.evaluate((evalVar) => {
  console.log('evalVar:', evalVar); // 2. should be defined now
  ...
}, evalVar); // 1. pass variable as an argument
Copy after login

Note that multiple variables can be passed by including additional arguments when calling page.evaluate(). It's important to ensure that all arguments are serializable as JSON or are JSHandles of in-browser objects. By following these guidelines, you can successfully pass variables into evaluation functions in Puppeteer and access them within the page's context.

The above is the detailed content of How to Pass Variables to Puppeteer's `page.evaluate()` Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template