theDavidBarton
theDavidBarton

Reputation: 8841

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.

Upvotes: 3

Views: 1483

Answers (1)

hardkoded
hardkoded

Reputation: 21607

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()));

Upvotes: 1

Related Questions