How to perform right click with Puppeteer?

房东的猫 提交于 2020-01-24 11:01:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!