Javascript onclick代理

问题描述

我要代理onclick事件

这是我尝试过的:

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

使用apply:陷阱,我可以使用上面的代码代理getElementById。但是,当我尝试代理onclick时,会出现Illegal invocation错误。如何修复我的代码

解决方法

HTMLElement.prototype.onclick是一个获取者/设置者。当您引用

HTMLElement.prototype.onclick

您使用HTMLElement.prototype的调用上下文来调用getter-但是getter期望 actual元素的调用上下文,因此它会抛出。

您可以改用Object.defineProperty-看起来不需要代理,只需拦截呼叫即可:

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