Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform right click with Puppeteer?

I'm trying to perform right-click with Puppeteer.

I've tried to add the option:

await component.click({ button: "right" })

But all I get is a regular click on the component. I followed Puppeteer's API.

What am I doing wrong?

like image 405
Yinon Avatar asked Jan 28 '23 09:01

Yinon


2 Answers

It is correct that you can use elementHandle.click() with the button option set to 'right' to right-click an element:

const example = await page.$('#example');

await example.click({
  button: 'right',
});

According to the Official Documentation for elementHandle.click():

This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. If the element is detached from DOM, the method throws an error.

We can verify this by looking at the source code for mouse.click(), and we can see that the button option is considered before being sent to Input.dispatchMouseEvent in the Chrome DevTools Protocol.

Another method you can use to right-click an element would be to use use page.click():

await page.click('#example', {
  button: 'right',
});

Alternatively, you can use page.evaluate() to right-click an element with JavaScript executed in the page DOM environment:

await page.evaluate(() => {
  const example = document.getElementById('example');
  const event = document.createEvent('MouseEvents');

  event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 2, null);

  example.dispatchEvent(event);
});
like image 196
Grant Miller Avatar answered Jan 29 '23 21:01

Grant Miller


if you want to use mouse,

 await page.mouse.click(160, 300, {delay: 1000, button: 'left'});

you can do this ya

like image 23
Jun Shi Yan Avatar answered Jan 29 '23 21:01

Jun Shi Yan