Re-bind onclick, on* event listeners for debugging

☆樱花仙子☆ 提交于 2020-06-23 08:13:26

问题


I want to monkeypatch event listener registrations.

I found this answer showing how to do it for addEventListener:

const nativeEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(...args) {
  if (this.matches('div') && args[0] === 'click') {
    console.log('listener is being added to a div');
    debugger;
  }
  nativeEventListener.apply(this, args);
}

// then, when an event listener is added, you'll be able to intercept the call and debug it:
document.querySelector('div').addEventListener('click', () => {
  console.log('clicked');
});

But this won't cover onclick, onkeydown, etc. assignments.

I don't know how to do the same for those, because

const nativeOnClick = HTMLElement.prototype.onclick;

Throws a TypeError

TypeError: 'get onclick' called on an object that does not implement interface HTMLElement.

Now I wonder if there is a special way to retrieve specifically the setter and getter for onclick etc. individually, but I've had no luck so far with my google searches.


回答1:


You can get the original setter function with:

const originalSetter = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onchange').set;

If you want to redefine a property, you should look at using Object.defineProperty().



来源:https://stackoverflow.com/questions/62238373/re-bind-onclick-on-event-listeners-for-debugging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!