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
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!