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;
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With