John Smith
John Smith

Reputation: 83

How to click on specific part of element puppeteer

Say I have an element that's 500 pixels wide, called 'selector'. How would I go about, for example, clicking on pixel 400?

According to the puppeteer docs, .hover() will hover over the middle of the element. And when I tested it using code like

const selector = await page.$('selector');
await selector.hover();
await selector.click();

sure enough, it clicked right on pixel 250. So clearly, the code exists to make this happen. I looked through the puppeteer docs, but couldn't find the source code I needed. Can anyone help?

Upvotes: 3

Views: 12208

Answers (1)

blex
blex

Reputation: 25634

Puppeteer provides a method to click on a specific pixel on the page (Mouse.click(x, y)). You could calculate where that is relative to your element's position:

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("http://yoursite.com");

  const elem = await page.$("#my-element");
  await clickOnElement(elem, 400);

  await page.screenshot({ path: "example.png" });

  await browser.close();

  // Clicks on an element at position x,y
  async function clickOnElement(elem, x = null, y = null) {
    const rect = await page.evaluate(el => {
      const { top, left, width, height } = el.getBoundingClientRect();
      return { top, left, width, height };
    }, elem);

    // Use given position or default to center
    const _x = x !== null ? x : rect.width / 2;
    const _y = y !== null ? y : rect.height / 2;

    await page.mouse.click(rect.left + _x, rect.top + _y);
  }
})();

Upvotes: 17

Related Questions