Can I remove event listeners with a Chrome extension?

后端 未结 2 1558
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-08 05:42

In Chrome\'s dev tools, there\'s a lovely interface where you can see all the event listeners attached to a given DOM element, and remove any of them as you see fit. Here\'s a s

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 05:58

    Unfortunately because of how event listeners are implemented, this isn't trivially possible. There are some libraries you can use which record calls to add event listeners, thereby giving you a reference to remove. Short of using those or rolling your own, the isn't a simple tool to remove them anonymously.

    You can however do something which will effectively remove all listeners, which is to clone the element and replace it with the clone. Cloning does not preserve any listeners on the element or its children, though it does otherwise preserve all attributes. Here's an example of how to do that:

    var elem = document.getElementById('foo'),
    clone = elem.cloneNode(true);
    elem.parentNode.replaceChild(clone, elem);    
    

提交回复
热议问题