How to Click on a Specific Coordinates of an Element

How to simulate a click by using x,y coordinates in JavaScript?

You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.

All modern browsers support document.elementFromPoint and HTMLElement.prototype.click(), since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:

document.elementFromPoint(x, y).click();
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

How to click element using x/y coordinates with puppeteer?

You can find the iframe and its coordinates, and then add the offset of the element you want inside this iframe, before clicking:

const puppeteer = require("puppeteer");

(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();

await page.goto("https://example.com/page_with_frame", {waitUntil: 'networkidle0'});

// Find the iframe
const frame = await page.waitForSelector("iframe");
// Find its coordinates
const rect = await page.evaluate(el => {
const {x, y} = el.getBoundingClientRect();
return {x, y};
}, frame);

// Values found manually by doing
// `document.querySelector('.yscp_link').getBoundingClientRect()`
// in the dev console. Add 5 to them, because it's the top left corner
const offset = {x: 213 + 5, y: 11 + 5};

// Click
await page.mouse.click(rect.x + offset.x, rect.y + offset.y);

await frame.waitForNavigation({
waitUntil: 'networkidle2',
});

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

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

How do I get the coordinates of a mouse click on a canvas element?

If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.

function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}

const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})


Related Topics



Leave a reply



Submit