You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Javascript如何针对指定URL的XHR请求修改其responseText响应内容

实现方案

你可以通过拦截XMLHttpRequest的open方法存储请求URL,再在responseText的getter中做匹配判断,即可实现仅修改指定请求返回值的需求,完整修改后的代码如下:

(function(http){
  // 保存原始open方法和responseText getter
  const originalOpen = http.prototype.open;
  const getResponseText = Object.getOwnPropertyDescriptor(
    http.prototype,
    'responseText'
  ).get;

  // 重写open方法存储当前请求的URL
  http.prototype.open = function(method, url, ...rest) {
    this._requestUrl = url;
    return originalOpen.apply(this, [method, url, ...rest]);
  };

  // 重写responseText的getter
  Object.defineProperty(
    http.prototype,
    "responseText",
    {
      get: function(){
        const originalText = getResponseText.apply(this, arguments);
        // 可根据需求调整匹配规则,以下为3种常见示例
        // 示例1:精确匹配指定URL
        // const isMatch = this._requestUrl === 'https://your-domain.com/api/getUser';
        // 示例2:URL包含指定字符串
        // const isMatch = this._requestUrl.includes('/api/user/info');
        // 示例3:正则匹配
        const isMatch = /^https?:\/\/.*\/api\/admin.*$/.test(this._requestUrl);

        // 匹配规则才修改返回值,否则返回原始内容
        if (isMatch) {
          return originalText + '{"Admin":true}';
        }
        return originalText;
      }
    }
  );
})(self.XMLHttpRequest);

改动说明

  • 新增对XMLHttpRequest.prototype.open的拦截,所有XHR请求发起时会把请求地址存入实例的_requestUrl属性,方便后续读取判断
  • 内置3种常见的URL匹配规则,不需要的规则直接注释掉即可,也可以自定义其他匹配逻辑
  • 仅当请求URL匹配规则时才修改返回值,其余请求完全不受影响,不会出现全局响应污染问题

内容的提问来源于stack exchange,提问作者DarklordX89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:36:03