Skip to content Skip to sidebar Skip to footer

How To Pass A Function / Variable In Puppeteer Page.$eval?

I am using Puppeteer to automatically fill a webform. Each time the name in the [input] field should change to a different name from an array. If I assign a name directly in the pa

Solution 1:

By reading the puppeteer's documentation, you can see where we can insert parameters.

We can see that the parameters are a spreaded array (...args) that is received in last.

page.$eval(selector, pageFunction[, ...args])

So we pass the selector then the function to be evaluated pageFunction and finally the arguments to the pageFunction the ...args.

await page.$eval('input[name=name]', (el, name) => { 
   el.value = name
}, name);
  • el is your element equivalent to document.querySelector('input[name=name]')
  • name is your parameter that will receive the names_for_array (or anything you want)
  • And lastly you pass the value to the parameter name

You can pass anything you want because name is a parameter. Example:

await page.$eval('input[name=name]', (el, name) => { 
   el.value = name
}, 'Michael');

Solution 2:

easy fix:

await page.$eval('input[name=name]', (el, name) => el.value = name, name_from_array);

Post a Comment for "How To Pass A Function / Variable In Puppeteer Page.$eval?"