我有一个名为 x() 的函数。我想在每次更改任意节点的innerHTML 属性时调用 x() (请注意,我希望为所有节点调用 x(),而不仅仅是 1 个节点)。最初,我认为innerHTML是HTMLElement对象的函数,并想对其进行猴子修补,但在Chrome的Javascript控制台中进行操作后,我未能在HTMLElement对象中找到innerHTML函数。
我还考虑过使用 DOMAttrModified 事件 (http://help.dottoro.com/ljdchxcl.php),但 Chrome 不支持它。欢迎提出任何建议。
最佳答案
@Cecchi 的答案很酷,但它不是一个真正的猴子补丁,全局适用于所有 HTMLElement 实例。自该答案以来,浏览器具有新功能。
这很棘手,因为 HTMLElement.prototype.innerHTML
是一个 setter,但我能够让它像这样工作:
//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
关于javascript - 在 Chrome 中拦截 [HTMLElement].innerHTML 修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14411288/