I’m thinking about ways of managing the behaviour of JavaScript on the client.
Suppose at the top of my HTML page, I have…
<script>
var XMLHttpRequest = function () {
this.send = function() {
alert(args.toString());
}
};
Is it subsequently possible (on the same page) to access the native XMLHttpRequest object?
(obviously, from a security viewpoint this is not the best way to prevent XSS – that’s not the question).
Since
XMLHttpRequestis a property of thewindowobject, you should still be able to access it through that.You have not actually overwritten it, you have only shadowed the native property of
windowso any time you try to callXMLHttpRequestin the scope of your declaration, your overridden version will be encountered first in the scope chain and therefore executed. If you explicity accesswindow.XMLHttpRequestyou will bypass your overridden version and access the native one directly:Note that if you had not declared your version with the
varkeyword, you would actually have overridden the native function, and in that case you can get it back (but not in Internet Explorer) by deleting the new property:Edit
I just realised the above is slightly misleading. If you omit the
varkeyword, you don’t actually overwrite the original function, you are still just shadowing it. That is because the original function is declared on the prototype of thewindowconstructor.