JS - 拦截某个 XMLHttpRequest 并触发一个函数
P粉314915922
P粉314915922 2024-04-03 15:33:25
0
1
396

我只是想根据发送的某个 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粉314915922
P粉314915922

全部回复(1)
P粉276876663

您需要添加 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);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!