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.
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()
.