Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding XMLHttpRequest's send method

I'm trying to log (and later modify) the data XMLHttpRequest sends to a server by overriding XMLHttpRequest.send function.

My function logs the data correctly to the console, however the request doesn't finish, therefore the browser keeps waiting for the response indefinitely.

Any ideas what's wrong with the code?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
like image 200
user1268760 Avatar asked Mar 14 '12 11:03

user1268760


People also ask

What are the types of send () method used for XMLHttpRequest?

send() The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.

What is new XMLHttpRequest ()?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.


1 Answers

You have forgot this:

this.realSend(vData);

However, you don't need to add a new method to the prototype:

var send = XMLHttpRequest.prototype.send;

XMLHttpRequest.prototype.send = function(data) {
    send.call(this, data);
}

Using closure, you can also avoid rogue variables:

!function(send){
    XMLHttpRequest.prototype.send = function (data) {
        send.call(this, data);
    }
}(XMLHttpRequest.prototype.send);
like image 171
ZER0 Avatar answered Oct 05 '22 20:10

ZER0