重新绑定onclick,on *事件侦听器以进行调试

问题描述 投票:1回答:1

我想猴子事件监听器注册。

我发现this answer显示了如何针对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');
});

但这不包括onclickonkeydown等分配。

我不知道该怎么做,因为

const nativeOnClick = HTMLElement.prototype.onclick;

引发TypeError

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

现在,我想知道是否有一种特殊的方法来分别检索特定地用于onclick等的setter和getter,但是到目前为止,我的Google搜索还没有运气。

javascript dom-events getter-setter setter
1个回答
0
投票

您可以使用以下方法获得原始的setter函数:

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

如果要重新定义属性,则应使用Object.defineProperty()

© www.soinside.com 2019 - 2024. All rights reserved.