1

我有一个名为 x() 的函数。每次更改任意节点的 innerHTML 属性时,我都想调用 x() (请注意,我希望为所有节点调用 x(),而不仅仅是 1 个节点)。最初,我认为 innerHTML 是 HTMLElement 对象的一个​​函数,并想对其进行修补,但在 Chrome 的 Javascript 控制台中玩耍后,我未能在 HTMLElement 对象中找到 innerHTML 函数。

我还考虑过使用 DOMAttrModified 事件(http://help.dottoro.com/ljdchxcl.php),但 Chrome 不支持它。欢迎任何建议。

4

2 回答 2

1

@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

于 2016-08-04T18:27:20.440 回答
0

根据您的开发目标和所需的浏览器支持(听起来就像 Chrome,希望只是现代 Chrome),您可以查看界面(示例从Mozilla Hacks 博客MutationObserver借用并稍作修改:

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
    x(mutation.target);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// select the target nodes
Array.prototype.slice.apply(
    document.querySelectorAll('.nodes-to-observe')
).forEach(function(target) {
    observer.observe(target, config);
});

// later, you can stop observing
observer.disconnect();

更多关于MutationObservers 的信息可以在这里找到:

https://developer.mozilla.org/en-US/docs/DOM/MutationObserver

这是在 Chrome 18 和 Firefox 14 中实现的。

于 2013-01-19T05:19:24.603 回答