javascript - 在 Chrome 中拦截 [HTMLElement].innerHTML 修改

标签 javascript google-chrome google-chrome-extension

我有一个名为 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/

相关文章:

javascript - 为什么这两个 javascript 二维数组的行为不同?

javascript - 将表格单元格属性传递给 Bootstrap 模态

javascript - 加载 AJAX 调用的 div 在 IE 或 Chrome 中不显示,在 Firefox 中工作正常

javascript - 我的 JS 文件无法加载到我的 Chrome 网络应用程序中

javascript - Chrome 扩展等待选项卡创建和选项卡内的脚本(异步问题)

google-chrome - 解压后的 Chrome 扩展程序会自动更新吗?

Javascript:全局变量=坏?

javascript - 将 php 数组呈现给客户端时出现 Jquery DataTable 错误

javascript - 如何在html中读取具有特殊字符的属性值

CSS 菜单下拉对齐方式在 Chrome 中不起作用