Reputation: 79
I am using puppeteer to listen to click events. I would also like to know the id of the html element clicked. How can I do so? My code right now is as follows:
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
let browser = await puppeteer.launch({ headless: false });
let page = await browser.newPage();
// Expose a handler to the page
await page.exposeFunction('onClick', ({ type, detail }) => {
console.log(`Event fired: ${type}, detail: ${detail}`);
});
// listen for events of type 'status' and
// pass 'type' and 'detail' attributes to our exposed function
await page.evaluateOnNewDocument(() => {
window.addEventListener('click', ({ type, detail }) => {
window.onClick({ type, detail });
});
});
await page.goto("https://www.facebook.com/login");
})();
Upvotes: 1
Views: 1632
Reputation: 1430
When adding an event listener, in the callback function, you can access the event
parameter, and subsequently access the event's target
to get the element that triggered the event. You can access the element's properties like id, class, etc. so your window's onClick
event listener's callback should go something like this
window.addEventListener('click', (e) => {
console.log(e.target.getAttribute("id"));
});
Upvotes: 1