如何覆盖appendChild()方法?

10
appendChild = function(message) {
    console.log("intercepted!");
}

使用上述代码似乎不起作用。

有人知道吗?


+1 很棒的问题;我学到了新东西。 - Plynx
因为我正在撰写关于书签小程序的硕士论文,现在我需要描述它的弱点以及黑客如何利用它。 - NoWhereToBeSeen
2个回答

16

你可能想要替换的是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"));

演示


小心,appendChild函数应该返回新添加的节点。我建议反转您函数内的代码,并返回f.apply()响应。 - Gaël Métais

4

覆盖原生函数是不明智的,但如果你确实这样做了,请确保你也返回附加的元素,以防止使用原生“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);
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接