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?

7
  • Any errors in the Javascript console? Commented Oct 13, 2014 at 23:26
  • Is it calling the original onreadystatechange function instead of your replacement? Commented Oct 13, 2014 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: stackoverflow.com/a/7987619/361684 Commented Oct 13, 2014 at 23:30
  • No errors in the console. And yes, it is calling the original instead. Commented Oct 13, 2014 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... Commented Oct 13, 2014 at 23:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 well there is clearly something else going on. Do you have a link to where its happening for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.