我想猴子事件监听器注册。
我发现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'); });
但这不包括onclick
,onkeydown
等分配。
我不知道该怎么做,因为
const nativeOnClick = HTMLElement.prototype.onclick;
引发TypeError
TypeError: 'get onclick' called on an object that does not implement interface HTMLElement.
现在,我想知道是否有一种特殊的方法来分别检索特定地用于onclick
等的setter和getter,但是到目前为止,我的Google搜索还没有运气。
您可以使用以下方法获得原始的setter函数:
const originalSetter = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onchange').set;
如果要重新定义属性,则应使用Object.defineProperty()
。