被覆盖后检索/恢复本机JavaScript函数



假设我们运行以下代码行

Object.defineProperty(HTMLElement.prototype, 'click', {value: null});

有什么方法可以检索/恢复原始click功能吗?

是的,我知道可以通过 dispatchEvent 触发点击事件,但是可以以类似的方式修补它。我问的是是否可以恢复点击事件或在像这样被覆盖后以某种方式触发该点击功能。假设该行代码是运行的第一行代码。

还原原始实现的一种方法是获取对另一个帧的命名空间的引用,并从该帧重用该实现。但是,如果页面在没有 allow-same-origin 标志的沙盒中运行,则此方法不起作用。

// Create a new execution context and get the implementation of "click".
var frame = document.createElement('iframe');
frame.sandbox = 'allow-same-origin';
document.body.appendChild(frame);
var click = frame.contentWindow.HTMLAnchorElement.prototype.click;
frame.remove();
var a = document.createElement('a');
a.href = 'https://example.com';
document.body.appendChild(a);
// Use the implementation.
click.call(a);
a.remove();

您可以保存旧函数并在以后恢复它:

var oldHandler = HTMLAnchorElement.prototype.click;
Object.defineProperty(HTMLAnchorElement.prototype, 'click', {
    value: null,
    configurable: true,
});
// do stuff...
Object.defineProperty(HTMLAnchorElement.prototype, 'click', { 
    value: oldHandler 
});

确保设置configurable: true,否则您将无法覆盖/恢复它。

最新更新