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

时间:2015-04-26 22:32:01

标签: javascript

假设我们运行以下代码行

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

有没有办法检索/恢复原始click功能?

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

2 个答案:

答案 0 :(得分:0)

您可以保存旧功能并稍后恢复:

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,否则您将无法覆盖/恢复它。

答案 1 :(得分:0)

恢复原始实现的方法是获取对另一个框架的命名空间的引用,并重新使用该框架中的实现。如果页面在没有allow-same-origin标记的sandbox中运行,则此方法不起作用。

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