用Reflect和Proxy批量hook原生对象的属性、方法
Object.assign(HTMLScriptElement.prototype, new Proxy(HTMLScriptElement.prototype, {
appendChild(txt) {
const s = txt.toString();
const isHandle = rule instanceof RegExp ? rule.test(s) : s.includes(rule);
if (!isHandle) return rawAppend(txt);
if (cb) {
txt.textContent = cb(s);
//return rawAppend(txt);
}
},
set(target, key, value, receiver) {
if (key == 'src') {
const rule = rules.find(r => value.includes(r.rule));
if (rule) return rule.callback(value);
}
Reflect.set(target, key, value, receiver);
}
}));
代码如上,assign方法失败,有简便巧妙些的办法吗
1 回复
Reflect.setPrototypeOf(HTMLScriptElement, new Proxy(HTMLScriptElement.prototype, {
...
}));
重新翻了一下文档,用Reflect.setPrototypeOf解决了