Intercept #AJAX “open” statements in #JavaScript

If you want to change the default behaviour of AJAX across your website, perhaps you want to make sure that every AJAX called is logged before executing, or that it is somehow audited for security before being called, you can use interceptor scripts in Javascript that override the default functionality of the XMLHttpRequest object that is behind every AJAX call, even if a library like JQuery is used ontop of it.

So, for instance, if you wanted to catch the body of all POST requests sent via AJAX, you could do this;

(function(send) {
XMLHttpRequest.prototype.send = function(body) {
var info=”send datarn”+body;
alert(info);
send.call(this, body);
};
})(XMLHttpRequest.prototype.send);

Or, if you wanted to change the destination of all AJAX requests such that all communications are sent via a logging service first, then you could do this;

(function(open) {
XMLHttpRequest.prototype.open = function(verb,url,async,user,password) {
open.call(this, verb,”https://somewhere.com/log”,async,user,password);
this.setRequestHeader(“X-Original-URL”, url);
};
})(XMLHttpRequest.prototype.open);

Where somewhere.com/log is obviously fictitious.

Hope this is useful to somebody!

Leave a Reply

Your email address will not be published.