如何在Puppeteer中执行右键单击? [英] How to perform right click with Puppeteer?

查看:450
本文介绍了如何在Puppeteer中执行右键单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Puppeteer进行右键单击.

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

我尝试添加选项:

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

但是我得到的只是定期单击该组件.我遵循了Puppeteer的 API .

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

我在做什么错了?

推荐答案

可以使用

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

根据elementHandle.click()的官方文档:

如果需要,此方法会将元素滚动到视图中,然后使用 page.mouse 单击元素的中心.如果该元素与DOM分离,则该方法将引发错误.

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.

我们可以通过查看源代码来验证这一点mouse.click() ,我们可以看到在将button选项发送到 Input.dispatchMouseEvent .

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.

可用于右键单击元素的另一种方法是使用 page.click() :

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

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

或者,您可以使用 page.evaluate() 右键单击在页面DOM环境中执行了JavaScript的元素:

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

这篇关于如何在Puppeteer中执行右键单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆