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?
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?
Share Improve this question asked Dec 20, 2011 at 18:50 Šime VidasŠime Vidas 186k65 gold badges286 silver badges391 bronze badges 1- @ЖΞЖ Using an iframe, as posted by Raynos. The inspiration for this question was this answer to one of my past questions... – Šime Vidas Commented Dec 20, 2011 at 19:10
1 Answer
Reset to default 29var 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.