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

如何Monkey-patch XMLHttpRequest.send实现仅为指定URL请求添加请求头

send方法执行时无法直接获取请求URL,请求URL是在调用open方法时传入的,因此你需要同时改写XMLHttpRequest.open方法,将URL暂存到XHR实例上,之后在send逻辑中读取该URL做匹配判断即可。

实现代码如下:

// 缓存原生方法
const originalOpen = window.XMLHttpRequest.prototype.open;
const originalSend = window.XMLHttpRequest.prototype.send;

// 重写open方法存储请求URL
window.XMLHttpRequest.prototype.open = function() {
  // open方法第二个参数为请求URL,存储到实例自定义属性上
  this._targetUrl = arguments[1];
  return originalOpen.apply(this, Array.prototype.slice.call(arguments));
};

// 重写send方法添加条件判断
window.XMLHttpRequest.prototype.send = function() {
  // 替换为你需要匹配的URL特征子串
  const matchKeyword = "your-target-domain.com/path";
  // 仅URL包含指定子串时添加自定义头
  if (this._targetUrl?.includes(matchKeyword)) {
    this.setRequestHeader("A-Header", "Value");
  }
  return originalSend.apply(this, Array.prototype.slice.call(arguments));
};

补充说明:

  • 自定义存储URL的属性名(示例中为_targetUrl)可以自行修改,只要不与XMLHttpRequest原生属性重名即可
  • 如果需要同时匹配多个规则,可以自行扩展判断逻辑,比如换成数组遍历匹配、正则匹配等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:24:05