1

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 page.$eval function (e.g. "Michael") everything works as expected.

   puppeteer.launch({ headless: false }).then(async browser => {
   const page = await browser.newPage()
   await page.goto('https://example.com/webform')
       
   await page.waitFor('input[name=name]');
   await page.$eval('input[name=name]', (el) => el.value = "Michael");

But as soon as I try to pass a variable or function (e.g. name_from_array)

var name = ["Michael", "Lisa", "Jason"]
const random = Math.floor(Math.random() * name.length);
var name_from_array = name[random];

puppeteer.launch({ headless: false }).then(async browser => {
const page = await browser.newPage()
await page.goto('https://example.com/webform')
   
await page.waitFor('input[name=name]');
await page.$eval('input[name=name]', (el) => el.value = name_from_array);

I get an error message saying "UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: name_from_array is not defined".

Any idea how to fix this issue?

Thanks a lot!

2 Answers2

3

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');
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
1

easy fix:

  await page.$eval('input[name=name]', (el, name) => el.value = name, name_from_array);
  • 4
    It would help if you could explain what the issue is and why this fixes the issue. – Emile Aug 18 '20 at 13:16
  • Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users also with similar issues. – FluffyKitten Aug 18 '20 at 17:49