恢复已被覆盖的内置方法

Šim*_*das 14 javascript browser theory

假设我们的脚本包含在网页中,之前的脚本(已经执行过)执行了此操作:

String.prototype.split = function () {
    return 'U MAD BRO?';
};
Run Code Online (Sandbox Code Playgroud)

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

我们想使用这种方法,所以我们需要以某种方式恢复它.当然,我们可以定义自己的方法实现并使用它.但是,为了这个问题,我们只想说我们真的想恢复浏览器对该方法的实现.

因此,浏览器具有该split方法的实现(在本机代码中,我相信),并且String.prototype.split无论何时加载新的网页,该实现都被分配.

我们想要实施!我们想要它回来String.prototype.split.

现在,我已经提出了一个解决方案 - 它是一个黑客攻击,它似乎正在工作,但它可能有缺陷,我将不得不测试一下......所以,在此期间,你能想出一个解决方案吗?这个问题?

Ray*_*nos 21

var iframe = document.createElement("iframe");
document.documentElement.appendChild(iframe);
var _window = iframe.contentWindow;
String.prototype.split = _window.String.prototype.split;
document.documentElement.removeChild(iframe);
Run Code Online (Sandbox Code Playgroud)

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

注意这种方法有陷阱.

"foo".split("") instanceof Array // false
"foo".split("") instanceof _window.Array // true
Run Code Online (Sandbox Code Playgroud)

解决这个问题的最好方法是instanceof永远不要使用.

另请注意,var _split = String.prototype.split作为<script>顽皮脚本之前的标签或不包括顽皮脚本,显然是一个更好的解决方案.

  • 我想在潜在的敌对环境中,可能会修补任何可写的东西,包括document.createElement,无法访问函数的原始版本,即Object.defineProperty和/或Object.freeze。 `window.open`,等等? (2认同)