Search code examples
javascriptxmlhttprequest

JS - Intercept A Certain XMLHttpRequest And Fire a Function


I am simply trying to fire a function based on a certain XMLHttpRequest being sent. I don't need to change or add anything to the request - just trigger another function that is in my codebase. The request is being sent by a website that is embedding my JS code. I don't have control over the overarching site. I have got the interceptor working for all calls, but I don't know enough about it to narrow it down by the below requirements.

Required - If the Request URL contains get-users
Required - If the Status Code: 200 
Optional - If the Request Method: GET

Not sure if I should be using the send and the send.call.

(function (send) {
        XMLHttpRequest.prototype.send = function (data) {
          console.log('Request', this);
          // If call url contains "get-users" && status code = 200 && possibly if the request method = get
          // {
          //   MyFunction()
          // }
          send.call(this, data);
        };
      })(XMLHttpRequest.prototype.send);

Solution

  • You need to add a if condition to check if the request URL contains "get-users" and the status code is 200.

    Like this below code :-

    (function (send) {
      XMLHttpRequest.prototype.send = function (data) {
        console.log('Request', this);
    
        this.onreadystatechange = function () {
          if (this.readyState === 4 && this.status === 200 && this.responseURL.includes('get-users')) {
            MyFunction();
          }
        };
    
        send.call(this, data);
      };
    })(XMLHttpRequest.prototype.send);