0

I am using page.$$eval to assess div#Menu in the browser context. I however need to pass the value in a const variable, myVar, into the browser context to perform comparisons within that context. However, I am running into a scoping issue when using $$eval. Is there a way around this?

Here is the code I made:

const myVar = 100;
const menuData = await page.$$eval("div#Menu", (Menu1) => {
   return Menu1.map((Menu1Element) => {
   console.log(myVar); //testing to see if myVar is passed into browser context
   ...
   })[0];
}).catch(console.error);

The error message I get => Error: Evaluation failed: ReferenceError: myVar is not defined

  • `page.$$eval(selector, pageFunction[, ...args])` you need to pass the variables as args and declare them in the pageFunction definition as well. This should be similar to answer here: https://stackoverflow.com/questions/46088351/puppeteer-pass-variable-in-evaluate – gp. Dec 14 '20 at 03:30

1 Answers1

0

This is the signature: page.$$eval(selector, pageFunction[, ...args])

So you can pass args as pageFunction args (3rd parameter onwards in $$eval and these will be passed as args to your function.

This is the updated code snippet.

const myVar = 100;
const menuData = await page.$$eval("div#Menu", (Menu1, varInsideFunction) => {
   return Menu1.map((Menu1Element) => {
   console.log(varInsideFunction); //testing to see if myVar is passed into browser context
   ...
   })[0];
}, myVar).catch(console.error);
gp.
  • 8,074
  • 3
  • 38
  • 39