Search code examples
javascriptasync-awaitparameter-passingpuppeteer

Puppeteer : how to pass argument to page evaluate?


I want to pass an argument to Puppeteer page evaluate method.

I might just be still struggling with async/await that I don't master,so my knowledge issue might be more general. Anyway Puppeteer is the current problem to be solved.

I have this snippet for updating a element. It works well:

await page.evaluate(
    () =>
      (document.querySelector(
        "selector"
      ).innerHTML = "WHATEVER")
  );

"WHATEVER" value comes from an outside variable. I need to pass it along to evaluate.

I tried with :

const value = "WHATEVER"
async function setValue(val) {
    console.log(val) //OK
    await page.evaluate(
      () =>{
        console.log(val) // KO  Error [ReferenceError]: val is not defined
        document.querySelector(
          "selector"
        ).innerHTML = val
      }
    );
  }
  await setValue(value) // KO

Why is val not defined? How to pass an argument to page evaluate in this case? Is there an alternative?


Solution

  • page.evaluate() is isolated from the Node.js environment, which means it does not have access to variables from your Node.js script scope. To pass an argument to the function you provide to page.evaluate(), you should include it as an additional parameter. In fact this is the method signature:

    page.evaluate(pageFunction, ...args);
    

    So u need to so something like this:

    const value = "WHATEVER"
    async function setValue(val) {
        console.log(val) //OK
        await page.evaluate(
          (val) => {
            console.log(val) // Should be OK now
            document.querySelector("selector").innerHTML = val
          },
          val // This is where you're passing the argument 'val' to the function in page.evaluate()
        );
    }
    await setValue(value)