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
相关产品推荐
相关产品推荐

