我想对事件监听器注册进行 Monkeypatch。
我找到了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: 'get onclick' called on an object that does not implement interface HTMLElement.
现在我想知道是否有一种特殊的方法可以专门分别检索onclick
等的setter和getter,但到目前为止我的运气还不好。谷歌搜索。
最佳答案
您可以通过以下方式获得原始的 setter 函数:
const originalSetter = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onchange').set;
如果您想重新定义属性,您应该考虑使用 Object.defineProperty()
.
关于javascript - 重新绑定(bind) onclick、on* 事件监听器以进行调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62238373/