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

前端 未结 3 1582
南旧
南旧 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);
    }
    
    0 讨论(0)
  • 2021-01-06 08:49

    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;
    
    0 讨论(0)
  • 2021-01-06 08:51

    As 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:

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

    0 讨论(0)
提交回复
热议问题