search

Home  >  Q&A  >  body text

JS - Intercept an XMLHttpRequest and trigger a function

I just want to trigger 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 in my codebase. The request is sent by the website that embeds my JS code. I have no control over the overall website. I've got the interceptor to work for all calls, but I don't know enough about it to narrow it down based on the following 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 use send and 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);

P粉314915922P粉314915922259 days ago537

reply all(1)I'll reply

  • P粉276876663

    P粉2768766632024-04-04 12:24:48

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

    Like the following 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);

    reply
    0
  • Cancelreply