Search code examples
javascriptes6-proxy

Javascript onclick proxy


I want to proxy onclick event

Here is what I tried:

HTMLElement.prototype.onclick = new Proxy(HTMLElement.prototype.onclick, {
  set: (target, thisArgs, argsList) => {
    console.log(thisArgs)
    return target.apply(thisArgs, argsList)
  }
}

using apply: trap, I could use the above code to proxy getElementById. But when I try to proxy onclick I get Illegal invocation error. How can I fix my code?


Solution

  • HTMLElement.prototype.onclick is a getter/setter. When you reference

    HTMLElement.prototype.onclick
    

    you invoke the getter, with a calling context of HTMLElement.prototype - but the getter expects a calling context of an actual element, so it throws.

    You could use Object.defineProperty instead - and there doesn't look to be any need for the proxy, just intercept the call:

    const { get, set } = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick');
    Object.defineProperty(HTMLElement.prototype, 'onclick', {
      set: function(newHandler) {
        console.log(newHandler)
        return set.call(this, newHandler)
      },
      get
    });
    
    document.body.onclick = () => console.log('foo');
    click