Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

When I try to use getEventListeners in puppeteerSharp I got getEventListeners is not defined error:

var result = await page.EvaluateExpressionHandleAsync("getEventListeners(document.forms[0].getElementsByTagName('button')[0])");

How to use getEventListeners within puppeteerSharp?

I found this for javascript:

const cdp = await page.target().createCDPSession();    
const listeners = await cdp.send('DOMDebugger.getEventListeners', { objectId });

and I tried to convert it back into C#:

var t = await page.EvaluateExpressionHandleAsync(@"document.forms[0].getElementsByTagName('button')[0]");
var client = await page.Target.CreateCDPSessionAsync();
var result = await client.SendAsync("DOMDebugger.getEventListeners", t.RemoteObject.ObjectId);

but it seems I'm doing something wrong and I did not find any clear documentation about this.

getEventListeners is a console utility that is not an available function to use in a script developers.google.com/web/tools/chrome-devtools/console/… – hardkoded Feb 20, 2021 at 16:44 @hardkoded here: stackoverflow.com/questions/63059096/… in the first answer, it seems he uses getEventListeners. but I do not know how to convert it back into c# – Inside Man Feb 21, 2021 at 3:25

I have found the solution, here it is for those who may be interested:

First, we should create a CDPSession like this:

var client = await page.Target.CreateCDPSessionAsync();

then we should Evaluate our script to get an element:

var body = await client.SendAsync("Runtime.evaluate", new { expression = "document.getElementsByTagName('input')[0]" });

and at last, we should use DOMDebugger with the element's objectId to get its event listeners:

var result = await client.SendAsync("DOMDebugger.getEventListeners", new { objectId = body["result"]["objectId"] });
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.