Home >Web Front-end >JS Tutorial >How to Correctly Pass Variables to Puppeteer's `page.evaluate()` Function?
In Puppeteer, the page.evaluate() function allows you to execute custom JavaScript on a web page within the browser. However, it's not immediately clear how to pass variables from Node to the page.evaluate() function for use within the evaluated code.
When attempting to pass a variable, the typical approach is to use the arrow function syntax:
However, if you encounter the error that evalVar is undefined within the arrow function, it means that the variable is not being passed into the function correctly.
To resolve this issue, variables must be passed as arguments to the page function. The adjusted syntax is:
Here, the variable evalVar is passed as an additional argument to the arrow function, making it accessible within the evaluated code.
This technique works for passing multiple variables as well. Simply add more arguments to the page.evaluate() function call:
It's important to ensure that the passed arguments are either serializable as JSON or are JSHandles of in-browser objects, as these are the supported types for passing variables to page.evaluate().
The above is the detailed content of How to Correctly Pass Variables to Puppeteer's `page.evaluate()` Function?. For more information, please follow other related articles on the PHP Chinese website!