Reputation: 2591
I'm developing a windows form application to parse and analyze web pages. I used webbrowser control. The web page has html and javascript code bellow. and my windows form has c# code. Here is the code:
HTML code:
<div id="div1" onclick='func1(this);'>
</div>
<div id="div2">
</div>
<div id="div3">
</div>
Javascript:
function func1(element) {
...
}
document.getElementById("div2").onclick = function foo() { doSomething(); }
document.getElementById("div3").addEventListener("click", anyFunc);
C# code in my windows form application after navigating the related URL:
HtmlElement el1 = WebBrowser.Document.GetElementById("div1");
HtmlElement el2 = WebBrowser.Document.GetElementById("div2");
HtmlElement el3 = WebBrowser.Document.GetElementById("div3");
String el1JavaFunc = el1.GetAttribute("onClick");
String el2JavaFunc = el2.GetAttribute("onClick");
String el3JavaFunc = el3.GetAttribute("onClick");
// check if el1JavaFunc is empty or null
// check if el2JavaFunc is empty or null
// check if el3JavaFunc is empty or null
In this way after checking the related string for each element, I can figure that if the element has assigned javascript function or not. This works for el1 and el2, but it returns null string for el3.
How could I figure that third element has assigned javascript function using addEventListener?
Upvotes: 0
Views: 954
Reputation: 4104
The DOM does not offer any API to retrieve a list of all eventListeners (reference) So it can't be done like that.
Perhaps you have control over the code that does the addEventListener() ? Then you could create a list of listeners there and use the list later on.
Upvotes: 0
Reputation: 5648
As if mentioned here: Check if an element has event listener on it. no jquery
There is no way to determine if an element is listening for an event or not, using JavaScript. The closest thing is getEventListeners(node), where node is the element you want to inspect. However this can only be used in Google chrome and only in the console. So it cannot be used in production.
Upvotes: 0
Reputation: 2783
I would suggest always calling .addEventListener anyway, because:
if multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Upvotes: 1