2013-01-10 96 views
7
appendChild = function(message) { 
    console.log("intercepted!"); 
} 

使用上面的代碼似乎不起作用。如何覆蓋appendChild()?

任何人都知道嗎?

+0

+1偉大的問題;我學到了一些新東西。 – Plynx

+0

因爲我正在寫關於bookmarklet的碩士論文,現在我需要描述它的弱點以及如何使用它。 – RedHotScalability

回答

13

你可能想要替換的是Element.prototype.appendChild,但這可能是一個壞主意。

本示例將文本intercepted在插入的元素:

var f = Element.prototype.appendChild; 
Element.prototype.appendChild = function(){f.apply(this, arguments);arguments[0].innerHTML="!Intercepted!"; }; 
document.body.appendChild(document.createElement("div")); 

Demonstration

+0

謝謝,我會在8分鐘內接受你的回答。 – RedHotScalability

2

這是不明智覆蓋原生的功能,但如果你這樣做不是要確保你返回附加元素以防止使用本機「appendChild」函數的返回值的代碼出現問題:

window.callbackFunc = function(elem, args) { 
    // write some logic here 
} 
window.f = Element.prototype.appendChild; 
Element.prototype.appendChild = function() { 
    window.callbackFunc.call(this, arguments); 
    return window.f.apply(this, arguments); 
};