I am doing browser automation using C#, and I would like to modify or possibly just eliminate event handlers on some of the html elements in webpages that I am looking at. E.g., suppose there is a button there which might (or might not) have an attached onClick event. How do I go about: - finding out if there are any event handlers attached to onClick for it? - removing them?
views:
284answers:
3As far as I know, it's not currently possible to use javascript to get all the event handlers attached to an element.
See this link for more info:
This depends on how the event handlers have been attached to the element.
If they are attached using addEventListener or one of the proprietary addWhatever listener methdos, there is no way to list them.
If they are attached by modifying the event property, ie. node.onclick = whatever, then you can read the value of the property to get the function and it'll work the same as any other JS func.
There is a third way too:
You can override the default addEventHandler/addListener behavior if the code you automate uses those. By doing this, you can replace the default behavior by one which pushes each handler into an array, which you can then loop over yourself.
The following code might 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);
}
Replacing element with its own clone should effectively discard all of its event listeners (well, technically listeners are still on an element, but since an element is replaced with its own clone, it looks as if listeners were simply removed):
el.parentNode.replaceChild(el.cloneNode(true), el);
Unfortunately, this won't work in IE, since IE erroneously transfers event listeners of an element on clone. To work around that you can reassign innerHTML
of element's parentNode
:
el.parentNode.innerHTML = el.parentNode.innerHTML;
Note that this will not only remove event listeners of an element, but also listeners of all of element's siblings.
Alternatively, you can work around IE issue by reassigning outerHTML
of an element:
el.outerHTML = el.outerHTML;