问题
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?
回答1:
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 );
});
来源:https://stackoverflow.com/questions/52610441/how-to-perform-right-click-with-puppeteer