@ 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
你究竟想要做什麼? –