首页  >  问答  >  正文

JS - 拦截某个 XMLHttpRequest 并触发一个函数

我只是想根据发送的某个 XMLHttpRequest 来触发一个函数。我不需要更改或添加任何内容到请求中 - 只需触发我的代码库中的另一个函数即可。该请求是由嵌入我的 JS 代码的网站发送的。我无法控制总体网站。我已经让拦截器适用于所有调用,但我对它了解不够,无法根据以下要求缩小范围。

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

不确定我是否应该使用 send 和 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粉314915922179 天前398

全部回复(1)我来回复

  • P粉276876663

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

    您需要添加 if 条件来检查请求 URL 是否包含“get-users”且状态码是否为 200。

    像下面的代码一样:-

    (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);

    回复
    0
  • 取消回复