1

I'm trying to make a script that will return a respond when data is received on the current page. (New Data Received > Log its content to the console)

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}
xhr.prototype.open = (function(fopen){
    return function(){
        console.log("Data received.");
        return fopen.apply(this,arguments); 
    }
})(XMLHttpRequest.prototype.open);

The above script is this script. (source)

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

Combine with this script. (source)

XMLHttpRequest.prototype.open = (function(fopen){
return function(){
    console.log("Data received.");
    return fopen.apply(this,arguments); 
}
})(XMLHttpRequest.prototype.open)

I wanted to know what I did wrong and how to make it work. Thanks!

phwt
  • 1,356
  • 1
  • 22
  • 42

2 Answers2

0

You're assigning to the prototype property of your instantiated object, not to the prototype of XMLHttpRequest. You might want to change XMLHttpRequest.prototype.onreadystatechange instead:

Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
  set: function(listenerFn) {
    this.addEventListener('readystatechange', function(...handlerArgs) {
      if (this.readyState == XMLHttpRequest.DONE) {
        // Custom action:
        // console.log(xhr.responseText);
        console.log('Detected a new response');
        // Run the previous callback that was passed in:
        listenerFn.apply(this, handlerArgs);
      }
    });
  }
});

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stacksnippets.net');
xhr.onreadystatechange = () => console.log('handler running');
xhr.send();

This isn't completely in line with the spec of course, this is just an example monkeypatch one might start with. (Mutating the built-in objects like XMLHttpRequest.prototype is bad practice, though - consider avoiding it if possible)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

This will log all xhr request

XMLHttpRequest.prototype.send = (function(fsend){
  return function(){
    this.addEventListener('load', function(){
      console.log("Data received.", this.response)
    }, {once: true})
    return fsend.apply(this, arguments); 
  }
})(XMLHttpRequest.prototype.send);

xhr = new XMLHttpRequest
xhr.open('GET', 'https://httpbin.org/get')
xhr.send()
Endless
  • 34,080
  • 13
  • 108
  • 131