Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out when a XMLHttpRequest request was made without callbacks

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?

like image 450
David Titarenco Avatar asked Feb 12 '10 21:02

David Titarenco


1 Answers

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.

like image 126
Bob Avatar answered Oct 26 '22 12:10

Bob