Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Overriding XMLHttpRequest

    Hi,

    I'm trying to get the following code to work. I'm intercepting all Ajax requests and responses by overriding XMLHttpRequest functions. The requests are alerted and sent correctly.

    I also get an alert box for responses, but after that I get an error "this.orsc is not a function", and the response is not delivered correctly. Any idea what the problem is?

    Code:
    XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
    var newSend = function(data) { alert("sent: " + data); if(this.onreadystatechange) { this.orsc = this.onreadystatechange; } this.onreadystatechange = newORSC; this.realSend(data); };
    var newORSC = function() { if (this.readyState == 4) { alert("response: " + this.responseText); } this.orsc(); };
    XMLHttpRequest.prototype.send = newSend;

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    By assigning newSend to the prototype of XMLHttpRequest you are correctly changing the scope to the prototype ... so "this" will refer to the current XMLHttpRequest object.

    But for newORSC you are not doing this. So most probably "this" will instead refer to the global window object ... which will obviously fail.

    Possible solution (untested): Change the scope for the newORSC object using .call()
    Code:
       var that = this;
       this.onreadystatechange = function() {newORSC.call(that);};

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    you have to assign the ready state change function before you call send, so your approach won't work.

    you might be able to modify open() to accomplish the same thing.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •