2013-01-19 37 views
1

我有一個名爲x()的函數。每當任意節點的innerHTML屬性發生變化時,我想調用x()(請注意,我希望x()被所有節點調用,而不僅僅是1個節點)。最初,我認爲innerHTML是HTMLElement對象的一個​​功能,並且想猴子修補它,但是在Chrome的Javascript控制檯中播放後,我未能在HTMLElement對象中找到innerHTML函數。在Chrome中攔截[HTMLElement] .innerHTML修改

我也想過使用DOMAttrModified事件(http://help.dottoro.com/ljdchxcl.php),但它在Chrome中不受支持。歡迎任何建議。

+0

你究竟想要做什麼? –

回答

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

0

取決於你正在爲你所需要的瀏覽器支持(這聽起來像不僅僅是Chrome,並希望只是現代的瀏覽器),你可以看看到MutationObserver接口(所示例借來稍微修改從Mozilla Hacks Blog

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(); 

更多MutationObserver S能在這裏找到:

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

這是在Chrome 18實施Firefox 14.