JS - Intercept an XMLHttpRequest and trigger a function
P粉314915922
P粉314915922 2024-04-03 15:33:25
0
1
488

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粉314915922
P粉314915922

reply all(1)
P粉276876663

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template