views:

141

answers:

2

I'm trying to overload the XMLHttpRequest.* method in JavaScript so a webpage can figure out if an Ajax request took place without using any intrusive callbacks. Now, something like this works relatively fine when using most JS frameworks:

XMLHttpRequest.prototype.getResponseHeader = function() {
 alert('O hai, looks like you made an AJAX request.');
}

However, there are two catches:

  • getResponseHeader can't be used as getResponseHeader anymore.
  • It doesn't work in simple AJAX examples. i.e. xmlhttp.open("GET","simple.html",false);

Is there any way JS can mirror XMLHttpRequest.open() or any way that I can chain something to it. I've tried a million paradigms (factory, cloning, wrapping -- most resulting in infinite recursion) and nothing seems to be working. Maybe it's just impossible. Any ideas?

+1  A: 

You can keep a reference to the original in some variable before you override the method and then call that variable within the function you overrode:

var temp = XMLHttpRequest.getResponseHeader;
XMLHttpRequest.getResponseHeader = function() { temp.apply(this, arguments); };

That should let you track uses without overriding the functionality provided by the original function.

Bob
the temp as parameter to apply should be `this` to maintain scope of the original call
Gaby
It would also be better to create this in a function scope so that the `temp` variable isn't place in the global scope
AnthonyWJones
Thanks Gaby, I've edited to reflect that. And Anthony: I always try to minimize globals, but as I only needed 2 lines of code to illustrate I didn't want to complicate things
Bob
Almost correct. You still need prototype manipulation: XMLHttpRequest.prototype.open = function() { XMLHttpRequestWrapper.apply(this, arguments); alert('It worked!'); }; -- but thanks for the elegant solution.
David Titarenco
A: 

XmlHttp is going to be a real problem, its a COM object and doesn't support the sort of prototype manipulation you want to use. Worse yet JQuery avoids XmlHttpRequest in IE even when its available it uses XmlHttp instead.

AnthonyWJones
About jQuery always using an ActiveX object in IE, even if `XMLHttpRequest` is available: not true, it does only do so if `protocol == "file:"`.
Marcel Korpel