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

前端 未结 3 1603
南旧
南旧 2021-01-06 08:10

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

3条回答
  •  遥遥无期
    2021-01-06 08:46

    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 methods, 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);
    }
    

提交回复
热议问题