Figuring out when a XMLHttpRequest request was made without callbacks
Asked Answered
T

2

6

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?

Tubbs answered 12/2, 2010 at 21:29 Comment(0)
E
2

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.

Emergency answered 12/2, 2010 at 21:52 Comment(4)
the temp as parameter to apply should be this to maintain scope of the original callAllegedly
It would also be better to create this in a function scope so that the temp variable isn't place in the global scopeFuscous
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 thingsEmergency
Almost correct. You still need prototype manipulation: XMLHttpRequest.prototype.open = function() { XMLHttpRequestWrapper.apply(this, arguments); alert('It worked!'); }; -- but thanks for the elegant solution.Tubbs
F
0

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.

Fuscous answered 12/2, 2010 at 22:16 Comment(1)
About jQuery always using an ActiveX object in IE, even if XMLHttpRequest is available: not true, it does only do so if protocol == "file:".Philippe

© 2022 - 2024 — McMap. All rights reserved.