4

I try 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);
    };
})();

The anonymous function never gets called. Why?

lenny.myr
  • 903
  • 2
  • 11
  • 20
  • Any errors in the Javascript console? – Barmar Oct 13 '14 at 23:26
  • Is it calling the original `onreadystatechange` function instead of your replacement? – Barmar Oct 13 '14 at 23:26
  • 2
    I tried to do the same thing before and hit some trouble with libraries. Here's how I got around the issues: http://stackoverflow.com/a/7987619/361684 – gilly3 Oct 13 '14 at 23:30
  • No errors in the console. And **yes**, it is calling the original instead. – lenny.myr Oct 13 '14 at 23:31
  • you are not initializing your XMLHttpRequest, but just defining some extra prototype overrides, which would in my opinion mean that your anonymous gets called, just that's all the action you are getting... – Icepickle Oct 13 '14 at 23:41
  • trivia: unk1 and unk2 are username and password – Winchestro Oct 14 '14 at 02:10
  • I don't get what you try to do? Are you trying to manipulate some library like jQuery? Because the original, default "onreadystatechange" property of the freshly constructed XMLHttpRequest instance is null and it can be redefined by libraries to whatever they want, including making it unwritable and unconfigurable – Winchestro Oct 14 '14 at 02:16

1 Answers1

3

It seems to work fine for me:

(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

Petah
  • 45,477
  • 28
  • 157
  • 213
  • Your example works for me too, but it does not work on the site I'm trying to use this technique on. Strange. – lenny.myr Oct 15 '14 at 17:57
  • @lenny.myr well there is clearly something else going on. Do you have a link to where its happening for you? – Petah Oct 15 '14 at 19:28