Chrome扩展中PATCH请求的details.requestBody始终为undefined问题排查
Chrome扩展中PATCH请求无法获取requestBody的问题排查
已知问题说明
Chrome的webRequest API在处理**分块编码(Transfer-Encoding: chunked)**的PATCH请求时,确实存在requestBody返回undefined的情况。这属于API的已知限制,相关行为在Chrome的bug反馈平台有大量记录,尤其常见于对接Dynamics 365这类API的场景。
POST请求通常不会触发该问题,因为这类请求的请求体多为一次性发送,而非流式分块传输,webRequest API能在onBeforeRequest阶段完整捕获。
排查步骤
- 确认请求编码方式:在Chrome开发者工具的Network面板中,查看PATCH请求的Request Headers,若存在
Transfer-Encoding: chunked,则可确定是分块编码导致的requestBody无法捕获。 - 检查Chrome版本:旧版本Chrome(如90.x及更早)对分块请求的处理存在缺陷,升级到最新稳定版可能解决问题。
替代解决方案
由于webRequest API对分块PATCH请求的限制无法通过权限或配置绕过,可通过以下方式捕获请求体:
方案1:通过Content Script拦截Fetch/XMLHttpRequest
在Content Script中重写全局的fetch或XMLHttpRequest方法,直接在请求发送前捕获请求体,再传递给Background Script:
Content Script代码(content.ts)
// 重写fetch方法 const originalFetch = window.fetch; window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { if (init?.method === 'PATCH' && init.body) { // 读取请求体内容 const bodyClone = init.body instanceof Blob ? init.body.clone() : init.body; const bodyText = await new Response(bodyClone).text(); // 发送到Background Script chrome.runtime.sendMessage({ type: 'CAPTURE_PATCH_BODY', url: typeof input === 'string' ? input : input.toString(), body: bodyText }); } return originalFetch(input, init); }; // 重写XMLHttpRequest(针对不使用fetch的场景) const originalXHR = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method: string, url: string) { if (method === 'PATCH') { const originalSend = this.send; this.send = function(body?: Document | XMLHttpRequestBodyInit | null) { if (body) { // 处理不同类型的请求体 if (typeof body === 'string') { chrome.runtime.sendMessage({ type: 'CAPTURE_PATCH_BODY', url, body: body }); } else if (body instanceof Blob) { const reader = new FileReader(); reader.onload = () => { chrome.runtime.sendMessage({ type: 'CAPTURE_PATCH_BODY', url, body: reader.result as string }); }; reader.readAsText(body); } } originalSend.call(this, body); }; } originalXHR.call(this, method, url); };
Background Script接收代码
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'CAPTURE_PATCH_BODY') { console.log('捕获到PATCH请求:', message.url); console.log('请求体:', message.body); // 这里可以处理请求体数据 } });
Manifest.json配置
需添加Content Script权限和匹配规则:
"content_scripts": [ { "matches": ["*://*.dynamics.com/api/data/v*"], "js": ["content.js"], "run_at": "document_start" } ], "permissions": [ "storage", "tabs", "webRequest", "sidePanel", "scripting" // 若需要动态注入Content Script则添加 ]
方案2:使用Declarative Net Request(限特定场景)
若仅需拦截请求而非读取请求体,可尝试chrome.declarativeNetRequest API,但该API无法直接获取请求体内容,仅能用于修改请求头或阻止请求。
内容的提问来源于stack exchange,提问作者Ivan Ficko
相关产品推荐
相关产品推荐

