恢复已被覆盖内置方法 [英] Recovering built-in methods that have been overwritten

查看:163
本文介绍了恢复已被覆盖内置方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我们的脚本包含在一个网页,和以前的脚本(已执行)这样做:

  String.prototype.split =功能(){
    返回'U MAD兄弟?;
};

因此​​,拆分字符串的方法已被覆盖。

我们想用这种方法,所以我们需要以某种方式恢复它。当然,我们可以只定义我们自己的这个方法的实现并使用它。然而,对于这个问题的缘故,我们只能说,我们真的想恢复浏览器的实现该方法的。

因此​​,浏览器有拆分方法的实现(在本地code,我相信),实施这一项目被分配到 String.prototype.split 每当一个新的网页加载。

我们想要的执行!我们希望它放回 String.prototype.split

现在,我已经想出了一个解决方案 - 这是一个黑客,它似乎是工作,但它可能有瑕疵,我会测试了一下......所以,在此期间,你能想出一个解决这个问题的?


解决方案

  VAR IFRAME =使用document.createElement(IFRAME);
document.documentElement.appendChild(IFRAME);
VAR _window = iframe.contentWindow;
String.prototype.split = _window.String.prototype.split;
document.documentElement.removeChild(IFRAME);

使用的iframe从主机对象恢复的方法。

请注意有陷阱用这种方法。

 foo的.split()的instanceof阵列//假
富.split()的instanceof _window.Array //真

解决这个问题的最好办法是不使用的instanceof ,直到永远。

另外请注意, VAR _split = String.prototype.split <脚本> 前的调皮标签脚本或的不包括的顽皮的脚本是obvouisly一个更好的解决方案。

Let's say that our script is included in a web-page, and a prior script (that already executed) did this:

String.prototype.split = function () {
    return 'U MAD BRO?';
};

So, the split string method has been overwritten.

We would like to use this method, so we need to recover it somehow. Of course, we could just define our own implementation of this method and use that instead. However, for the sake of this question, let's just say that we really wanted to recover the browser's implementation of that method.

So, the browser has an implementation of the split method (in native code, I believe), and this implementation is assigned to String.prototype.split whenever a new web-page is loaded.

We want that implementation! We want it back in String.prototype.split.

Now, I already came up with one solution - it's a hack, and it appears to be working, but it may have flaws, I would have to test a bit... So, in the meantime, can you come up with a solution to this problem?

解决方案

var iframe = document.createElement("iframe");
document.documentElement.appendChild(iframe);
var _window = iframe.contentWindow;
String.prototype.split = _window.String.prototype.split;
document.documentElement.removeChild(iframe);

Use iframes to recover methods from host objects.

Note there are traps with this method.

"foo".split("") instanceof Array // false
"foo".split("") instanceof _window.Array // true

The best way to fix this is to not use instanceof, ever.

Also note that var _split = String.prototype.split as a <script> tag before the naughty script or not including the naughty script is obvouisly a far better solution.

这篇关于恢复已被覆盖内置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆