1

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)

2 Answers 2

5

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 });
3
  • it do double click but its speed is not like real human being that is why its not triggering the double click that is required which ultimately does not add object in the workspace. Commented Oct 16, 2020 at 9:45
  • You can use delay like await page.mouse.click(rect.x, rect.y, { clickCount: 2, delay: 100 });. to wait 100ms between the two clicks Commented Oct 16, 2020 at 9:51
  • Thanks for this, it sent me in the right direction, but it turns out this does not create two clicks. This creates a single click which registers as a click with clickCount: 2. So, to actually do a double-click, we need to call page.mouse.click twice: once with clickCount: 1, and once with clickCount: 2 and delay: 100
    – jleven
    Commented Apr 5, 2021 at 22:13
4

You can also just do:

await page.click(selector, { clickCount: 2 });

as mentioned here

Not the answer you're looking for? Browse other questions tagged or ask your own question.