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

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

问题描述

假设我们的脚本包含在一个网页中,并且之前的脚本(已经执行)做到了这一点:

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?';
};

因此,split 字符串方法已被覆盖.

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.

因此,浏览器有一个 split 方法的实现(我相信在本机代码中),并且这个实现被分配给 String.prototype.split 每当新网页已加载.

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.

我们想要那个实现!我们希望它回到 String.prototype.split 中.

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

使用 iframe 从宿主对象中恢复方法.

Use iframes to recover methods from host objects.

注意这个方法有陷阱.

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

解决此问题的最佳方法是永远不要使用instanceof.

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

另请注意,var _split = String.prototype.split 作为

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