直接代理 window 或 globalThis 大概率失败,因其全局 API 多为不可配置、不可写的内置方法,且 Proxy 仅支持对象目标,而 window 在 iframe 等环境中可能非标准对象;应改为精准劫持 fetch、XMLHttpRequest.prototype.send 等函数入口,并逐个重定义 console 方法。

为什么直接代理 window 或 globalThis 大概率失败
因为多数全局 API(如 fetch、XMLHttpRequest、console.error)不是直接挂在 window 上的“可写属性”,而是不可配置(configurable: false)、不可写(writable: false)的内置方法。直接对 window 做 new Proxy(window, {...}) 会触发 TypeError: Cannot create proxy with a non-object as target 或静默失效——Proxy 只能代理对象,而 window 在某些上下文(如 iframe、Web Worker)中甚至不是标准对象。
真正可行的路径是:不代理全局对象本身,而是精准拦截你关心的**函数调用入口**,并确保它们在执行前被包裹。
- 优先劫持
fetch和XMLHttpRequest.prototype.send,覆盖 90% 的请求日志需求 -
console方法需逐个重赋值(不能靠 Proxy),因为console是 host object,其方法绑定到特定 context - 避免代理
setTimeout/setInterval,除非你明确要采集定时器调度链路——它会显著拖慢性能且易引发递归代理
如何安全劫持 fetch 并保留原始行为
核心是用 Object.defineProperty 替换原生 fetch,并在新函数中调用 originalFetch.apply(this, args),而不是简单地 originalFetch(...args)——后者会丢失 this 绑定(虽然 fetch 不依赖 this,但保持模式统一更稳妥)。
const originalFetch = window.fetch;
window.fetch = function(...args) {
const [input, init] = args;
const url = typeof input === 'string' ? input : input?.href || '';
<p>// 采集日志:时间、URL、method、是否跨域等
console.log('[fetch]', { url, method: (init?.method || 'GET').toUpperCase() });</p><p>return originalFetch.apply(this, args)
.then(res => {
console.log('[fetch-response]', { url, status: res.status });
return res;
})
.catch(err => {
console.error('[fetch-error]', { url, err });
throw err;
});
};- 不要在
fetch拦截里做异步日志上报(如发另一个fetch),否则可能触发竞态或循环采集 - 如果项目用了
AbortController,记得透传 signal,否则中断逻辑会失效 - SSR 环境下
window.fetch不存在,需加if (typeof window !== 'undefined')守卫
怎样无损替换 XMLHttpRequest 的 send 方法
XMLHttpRequest.prototype.send 是实例方法,必须代理原型链上的方法,而非某个实例。直接改写 prototype.send 是最轻量、兼容性最好的方式(IE10+ 都支持)。
立即学习“前端免费学习笔记(深入)”;
const originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
// 从 this 对象上提取 open 时设置的参数(需提前 patch open)
const { _url, _method, _headers } = this;
console.log('[xhr-send]', { url: _url, method: _method, headers: _headers });
<p>const startTime = Date.now();
const originalOnLoad = this.onload;
const originalOnError = this.onerror;</p><p>this.onload = function() {
console.log('[xhr-load]', { url: _url, duration: Date.now() - startTime });
if (originalOnLoad) originalOnLoad.call(this);
};</p><p>this.onerror = function() {
console.error('[xhr-error]', { url: _url });
if (originalOnError) originalOnError.call(this);
};</p><p>return originalSend.call(this, body);
};- 必须先 patch
XMLHttpRequest.prototype.open,把url、method存到this._url等临时字段,否则 send 时拿不到上下文 - 不要覆盖
onreadystatechange,它比 onload/onerror 更底层,容易漏掉状态;优先监听 onload/onerror - 注意 CORS 场景下,
responseText和response在 error 回调中不可读,日志里别硬取
为什么 console 方法不能用 Proxy,而必须逐个重定义
console 是浏览器注入的宿主对象(host object),它的方法(如 console.log)不是普通函数,typeof console.log === 'function' 为 true,但 console.log.toString() 通常返回 [native code],且无法通过 Object.getOwnPropertyDescriptor(console, 'log') 获取有效 descriptor(尤其在旧版 Safari 中)。Proxy 对这种对象无效。
唯一可靠做法是缓存原方法引用,再重新赋值:
['log', 'warn', 'error', 'info'].forEach(method => {
const original = console[method];
console[method] = function(...args) {
// 采集日志上下文:调用栈、时间、标签
const stack = new Error().stack?.split('\n')[2]?.trim() || '';
console.log('[console]', { method, args, stack });
return original.apply(console, args);
};
});- 不要覆盖
console.table或console.group,它们行为复杂,容易破坏调试体验 - 若项目用了第三方日志库(如 Sentry 的
Sentry.init({ integrations: [new BrowserTracing()] })),注意避免双重采集冲突 - 生产环境建议加开关控制是否启用 console 拦截,默认关闭——它对性能影响比 fetch/xhr 显著得多
全链路日志真正的难点不在“怎么挂”,而在“怎么不干扰”。每个被拦截的 API 都要确保:调用链不中断、this 和 arguments 不错位、错误不吞掉、异步流不污染。最常被忽略的是 polyfill 兼容性——比如你 patch 了 fetch,但项目又加载了 whatwg-fetch,结果原生 fetch 被覆盖两次,日志重复或丢失。上线前务必在真实 polyfill 环境中验证拦截点是否唯一生效。

















