简体   繁体   中英

How to double click in Puppeteer

I have a workspace in which I can add different objects. There is a scenario in which on double click, an object can be automatically added in the workspace. I have gone through different solutions but none of them really worked.

This is what I have tried:

await page.evaluate(selector => {
  var targLink = document.querySelector(selector);
  var clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent('dblclick', true, true);
  targLink.dispatchEvent(clickEvent);
}, selector)

You can use mouse.click(x, y[, options]) .


First get x and y .

const selector = "#elementID";

const rect = await page.evaluate((selector) => {
  const element = document.querySelector(selector);
  if (!element) return null;
  const { x, y } = element.getBoundingClientRect();
  return { x, y };
}, selector);

Then pass clickCount as an option to simulate double click.

await page.mouse.click(rect.x, rect.y, { clickCount: 2 });

Full code:

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();

  const page = await browser.newPage();

  await page.goto("https://www.example.com", {
    waitUntil: "domcontentloaded",
  });

  const selector = "#elementID";

  const rect = await page.evaluate((selector) => {
    const element = document.querySelector(selector);
    if (!element) return null;
    const { x, y } = element.getBoundingClientRect();
    return { x, y };
  }, selector);

  if (rect) {
    await page.mouse.click(rect.x, rect.y, { clickCount: 2 });
  } else {
    console.error("Element Not Found");
  }

  await browser.close();
})();

Update

You can add delay between the two clicks by use delay option. The code below will click double clicks to element with 100ms delay.

await page.mouse.click(rect.x, rect.y, { clickCount: 2, delay: 100 });

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