Can I programmatically examine and modify Javascript event handlers on html elements?

I am using browser automation with C #, and I would like to change or maybe just remove the event handlers on some html elements in the web pages that I am viewing. For example, suppose there is a button that may (or may not have) an onClick event attached. How can I: - find out if there are any event handlers attached to onClick? - removing them?

+4
javascript browser events
Sep 17 '09 at 5:22
source share
3 answers

Replacing an element with its own clone should effectively discard all its event listeners (well, technically the listeners are still on the element, but since the element has been replaced with its own clone, it looks like the listeners were simply deleted):

el.parentNode.replaceChild(el.cloneNode(true), el); 

Unfortunately, this will not work in IE, since IE mistakenly passes event listeners for the element on the clone. To get around this, you can reassign the innerHTML of the parentNode element:

 el.parentNode.innerHTML = el.parentNode.innerHTML; 

Note that this will not only remove event listeners for the element, but also listeners for all sibling elements.

Alternatively, you can work around the IE problem by reassigning the outerHTML element:

 el.outerHTML = el.outerHTML; 
+3
Sep 17 '09 at 6:16
source share

As far as I know, it is currently not possible to use javascript to get all event handlers attached to an element.

See this link for more information:

http://www.howtocreate.co.uk/tutorials/javascript/domevents

0
Sep 17 '09 at 5:39
source share

It depends on how the event handlers were attached to the element.

If they are connected using addEventListener or one of the listener's own addWhatever methods, there is no way to list them.

If they are attached by changing the property of the event, i.e. node.onclick = whatever, then you can read the value of the property to get the function, and it will work just like any other JS function.

There is a third way:

You can override the default behavior of addEventHandler / addListener if the code you are using automates. By doing this, you can replace the default behavior with one that pushes each handler into an array, which you can then iterate through yourself.

The following code may work:

 var oldAddEventListener = HTMLElement.prototype.addEventListener; HTMLElement.prototype.addEventListener = function(event, handler, bubbling) { /* do whatever you want with event parameters */ oldAddEventListener.call(this, event, handler, bubbling); } 
0
Sep 17 '09 at 6:07
source share



All Articles