Puppeteer: pass variable in .evaluate()

puppeteer page.evaluate example
puppeteer page.evaluate return value
puppeteer evaluate pass function
page.evaluate not working
page.evaluate pass arguments
puppeteer timeout
puppeteer document queryselector example
puppeteer wait

I'm trying to pass a variable into a page.evaluate() function in Puppeteer, but when I use the following very simplified example, the variable evalVar is undefined.

I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the page.evaluate() function so I can use it inside.

const puppeteer = require('puppeteer');

(async() => {

  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  const evalVar = 'WHUT??';

  try {

    await page.goto('https://www.google.com.au');
    await page.waitForSelector('#fbar');
    const links = await page.evaluate((evalVar) => {

      console.log('evalVar:', evalVar); // appears undefined

      const urls = [];
      hrefs = document.querySelectorAll('#fbar #fsl a');
      hrefs.forEach(function(el) {
        urls.push(el.href);
      });
      return urls;
    })
    console.log('links:', links);

  } catch (err) {

    console.log('ERR:', err.message);

  } finally {

    // browser.close();

  }

})();

You have to pass the variable as an argument to the pageFunction like this:

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

  console.log(evalVar); // should be defined now
  …

}, evalVar);

The arguments can also be serialized: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args.

Puppeteer Pass variable in .evaluate() - Mario, While learning and practicing with puppeteer I run into a problem that I thought was difficult to solve. Puppeteer Pass variable in .evaluate(). If I understand it correctly, puppeteer has to marshal the code in your evaluate function ultimately as a string and inject it into to page context. You can't pass function references or anything non-serializable across that boundary.

I encourage you to stick on this style, because it's more convenient and readable.

let name = 'jack';
let age  = 33;
let location = 'Berlin/Germany';

await page.evaluate(({name, age, location}) => {

    console.log(name);
    console.log(age);
    console.log(location);

},{name, age, location});

Passing variable to page.$$eval is not working · Issue #5165 , Run the script with the selector variable gives an error Tell us about your const browser = await puppeteer.launch({headless: false}); a catch block, or by rejecting a promise which was not handled with .catch(). Internally $eval calls $ and then evaluate , returning the value of the evaluate function. Puppeteer: pass variable in .evaluate() Puppeteer evaluate function; allow to pass a parameterized funciton as a string to page.evaluate; Functions bound with page.exposeFunction() produce unhandled promise rejections; How to pass a function in Puppeteers .evaluate() method? How can I dynamically inject functions to evaluate using Puppeteer?

Single Variable:

You can pass one variable to page.evaluate() using the following syntax:

await page.evaluate(example => { /* ... */ }, example);

Note: You do not need to enclose the variable in (), unless you are going to be passing multiple variables.

Multiple Variables:

You can pass multiple variables to page.evaluate() using the following syntax:

await page.evaluate((example_1, example_2) => { /* ... */ }, example_1, example_2);

Note: Enclosing your variables within {} is not necessary.

allow to pass a parameterized funciton as a string to page.evaluate , await page.evaluate(`console.log(arguments);`, 'FOO'); produces ReferenceError: One workaround is to prefix all clashing variables with window. Puppeteer uses DevTools Protocol, which requires you to pass a stringified function. run = async() =>{ const browser = await puppeteer.launch({headless  Does the code run properly without puppeteer? I mean, can you manually execute the code first on your browser and see what happens? and, is myFunction a promise? page.evaluate will just evaluate something and if it's a promise it'll wait for the promise to return. So if myFunction is not a promise, you are expecting the wrong return.

It took me quite a while to figure out that console.log() in evaluate() can't show in node console.

Ref: https://github.com/GoogleChrome/puppeteer/issues/1944

everything that is run inside the page.evaluate function is done in the context of the browser page. The script is running in the browser not in node.js so if you log it will show in the browsers console which if you are running headless you will not see. You also can't set a node breakpoint inside the function.

Hope this can help.

Puppeteer: pass variable in .evaluate(), I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the page.evaluate() function so I can use it  j'essaie de passer une variable dans un page.evaluate() function Marionnettiste, mais quand j'utilise l'exemple suivant très simplifié, la variable evalVar n'est pas défini. Je suis nouveau chez Puppeteer et je ne trouve aucun exemple sur lequel construire, donc j'ai besoin d'aide pour passer cette variable dans le page.evaluate() fonction

For pass a function, there are two ways you can do it.

// 1. Defined in evaluationContext
await page.evaluate(() => {
  window.yourFunc = function() {...};
});
const links = await page.evaluate(() => {
  const func = window.yourFunc;
  func();
});


// 2. Transform function to serializable(string). (Function can not be serialized)
const yourFunc = function() {...};
const obj = {
  func: yourFunc.toString()
};
const otherObj = {
  foo: 'bar'
};
const links = await page.evaluate((obj, aObj) => {
   const funStr = obj.func;
   const func = new Function(`return ${funStr}.apply(null, arguments)`)
   func();

   const foo = aObj.foo; // bar, for object
   window.foo = foo;
   debugger;
}, obj, otherObj);

You can add devtools: true to the launch options for test

Puppeteer: pass variable in .evaluate(), I'm trying to pass a variable into a page.evaluate() function in Puppeteer, but when I use the following very simplified example, the variable evalVar is undefined. Puppet allows a given variable to be assigned a value only one time within a given scope. This is a little different from most programming languages. This is a little different from most programming languages.

javascript, Puppeteer: pass variable in .evaluate (). Eu estou tentando passar uma variável em uma função page.evaluate() em Puppeteer , mas quando eu uso o seguinte  Environment Variables. Puppeteer looks for certain environment variables to aid its operations. If Puppeteer doesn't find them in the environment during the installation step, a lowercased variant of these variables will be used from the npm config.

Puppeteer documentation, Puppeteer looks for certain environment variables to aid its operations. If Puppeteer executablePath() is affected by the PUPPETEER_EXECUTABLE_PATH and args <Array<string>> Additional arguments to pass to the browser instance. const result = await page.evaluate(​x => { return Promise.resolve(8 * x); }, 7);  As all functions the generate function runs on the master, so your program will also execute on the puppet master. You have to provide a full qualified executable to the function (as a string; so use quotes) and possible arguments.

Puppeteer: pass variable in .evaluate(), I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the page.evaluate() function so I can use it inside. const​  A variable defined in DEFINE can be overridden by a variable defined in EVALUATE and/or locally to any other DAX expression. In the following example, the first EVALUATE returns the purple or azure color products, whereas the second EVALUATE uses another definition of the SelectedColors variable including only the red and white color names.

Comments
  • Hello, how would you pass multiple variables?
  • Also, I’m not really able to pass a function: var myFunction = function() { console.log("hello") }; await page.evaluate(func => func(), myFunction); gives me: Evaluation failed: TypeError: func is not a function.. Why?
  • Don't forget to type evalVar both in the function argument signature, and as a passed argument to evaluate (at the end of the code example).
  • @chitzui: You can't pass a function to pate.evaluate(). You can supposedly 'expose' it with page.exposeFunction. For more, see stackoverflow.com/a/58040978.
  • And I wanted to pass an object?
  • How would you add an argument in the 2nd case? eg I want to add pass a string to yourFunc
  • You can replace yourFunc with object If your property is not a function. @tramada
  • func is similar to youFunc,so you can call func(stringArg) just like exec yourFunc @user3568719
  • Would you mind showing how you would pass an object to window and then access it?