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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 17:42:11273browse

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

Variables in page.evaluate() Functions

Puppeteer's page.evaluate() function is a versatile tool for executing JavaScript within a page's execution context. However, passing variables into this function can be tricky.

Undefined Variables

When you try to access a variable within a page.evaluate() function, you might encounter the error "evalVar: undefined". This is because variables defined outside the function are not accessible within it.

Passing Variables via Arguments

To solve this issue, pass the variable as an argument to the page function like this:

const links = await page.evaluate((evalVar) => {

  console.log(evalVar); // 2. Should be defined now

  ...

}, evalVar); // 1. Pass the variable as an argument

Multiple Variables

You can also pass in multiple variables by adding more arguments to page.evaluate():

await page.evaluate((a, b, c) => { console.log(a, b, c) }, a, b, c)

Serializable Parameters

The arguments you pass must be either serializable to JSON or be JSHandles of in-browser objects. For details, refer to the official Puppeteer documentation: https://pptr.dev/#?show=api-pageevaluatepagefunction-args.

The above is the detailed content of How Can I 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