Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: performing element.click() inside page.$eval

The page.$eval and page.$$eval methods both return a value if the pageFunction itself returns a promise (I suppose it is a very rare case with puppeteer if they would not, most puppeteer methods return promises).

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

Documented use cases are all returning a value:

const divCount = await page.$$eval('div', divs => divs.length);
const options = await page.$$eval('div > span.options', options => options.map(option => option.textContent));

Question

But can we use page.$eval/page.$$eval to perform methods that only interacts with the browser without returning usable value (like element.click), especially if for a very similar reason we consider it a bad practice to use Array.map when we aren't using the returned array? I am curious because like this we could simplify scenarios where usage of Array.forEach is problematic.

It does work, but should we use it?

const clickAll = await page.$$eval('button', links => links.forEach(link => link.click()));

Note: Making it a const makes very less sense to me as we cannot use the clickAll reference anywhere else. I'd rather use it in itself without declaring it.

like image 408
theDavidBarton Avatar asked Feb 10 '26 20:02

theDavidBarton


1 Answers

You could consider this as a normal javascript function it could return a value or not, and you could use that return function or not. You don't need that clickAll variable.

await page.$$eval('button', links => links.forEach(link => link.click()));
like image 56
hardkoded Avatar answered Feb 14 '26 21:02

hardkoded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!