简体   繁体   中英

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?

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

if you want to use mouse,

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

you can do this ya

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM