Javascript XMLHttpRequest change onreadystatechange callback

I am trying to change the onreadystatechange callback. My javascript looks like this

(function() {
    var open_original = XMLHttpRequest.prototype.open;
    var send_original = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method, url, async, unk1, unk2) {
        // console.log(url);
        open_original.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(data) {
        this.onreadystatechange = function() {
            console.log('asdasdh adzl8 ada');
        }
        send_original.apply(this, arguments);
    };
})();

An anonymous function is never called. Why?

+4
source share
1 answer

Everything seems to be in order:

(function() {
    var open_original = XMLHttpRequest.prototype.open;
    var send_original = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method, url, async, unk1, unk2) {
        open_original.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(data) {
        this.onreadystatechange = function() {
            console.log('Works for me.');
        }
        send_original.apply(this, arguments);
    };
})();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/echo/html/', true);
xmlhttp.send();

http://jsfiddle.net/ers2s80a/

Screen shot

+3
source

All Articles