简体   繁体   English

如何在 puppeteer 中使用单击事件侦听器查找元素 ID

[英]How to find element id using click event listener in puppeteer

I am using puppeteer to listen to click events.我正在使用 puppeteer 来监听点击事件。 I would also like to know the id of the html element clicked.我还想知道单击的 html 元素的 ID。 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");

})();

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.添加事件监听器时,在回调函数中,可以访问event参数,进而访问事件的target ,获取触发事件的元素。 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您可以访问元素的属性,如 id、class 等,因此您窗口的onClick事件侦听器的回调应该是这样的

window.addEventListener('click', (e) => {
        console.log(e.target.getAttribute("id"));
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM