@Cecchi 的回答很酷,但它不是一个真正的猴子补丁,它全局适用于所有 HTMLElement 实例。自该答案以来,浏览器具有新功能。
这很棘手,因为HTMLElement.prototype.innerHTML
它是一个二传手,但我能够让它像这样工作:
//create a separate JS context that's clean
var iframe = document.createElement('iframe');
//have to append it to get access to HTMLElement
document.body.appendChild(iframe);
//grab the setter. note that __lookupSetter__ is deprecated maybe try getOwnPropertyDescriptor? anyways this works currently
let origSetter = iframe.contentWindow.HTMLElement.prototype.__lookupSetter__('innerHTML');
//mangle the global HTMLElement in this JS context
Object.defineProperty(HTMLElement.prototype, 'innerHTML', {
set: function (val) {
console.log('innerHTML called', val);
// *** do whatever you want here ***
return origSetter.call(this, val); //allow the method to be called like normal
}
});
现在来测试它:
document.createElement('div').innerHTML = '<p>oh, hey</p>';
//logs: innerHTML called <p>oh, hey</p>
这是一个 JSBin http://jsbin.com/qikoce/1/edit?js,console