Chrome扩展V3中Fetch API实现上传进度的方案问询
Chrome扩展V3上传进度监听解决方案
你提到的「Fetch API上传流支持尚未就绪」的结论不完全准确——Fetch本身确实没有提供像XHR那样直接的upload.progress事件,但并非只能等待功能完善,有两个可行的替代方案:
方案1:直接使用原生XHR(推荐)
Chrome扩展V3并没有禁用原生XMLHttpRequest,只是限制了同步XHR在后台页面等场景的使用,前台页面或内容脚本中完全可以正常使用原生XHR实现上传进度监听,不需要依赖jQuery的Ajax。示例代码:
// 假设已获取到目标文件对象 const file = document.querySelector('input[type="file"]').files[0]; const formData = new FormData(); formData.append('file', file); const xhr = new XMLHttpRequest(); // 监听上传进度 xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const progress = (e.loaded / e.total) * 100; console.log(`上传进度:${progress.toFixed(2)}%`); // 此处更新进度条UI } }); xhr.open('POST', '你的上传接口地址'); xhr.send(formData);
方案2:基于Fetch + ReadableStream手动追踪进度
如果必须使用Fetch,可以通过将文件拆分为可读取的流,手动统计已发送的字节数来计算进度,但这个方案实现更复杂,且需确保服务端支持分块上传:
async function uploadFileWithProgress(file, url) { let uploadedBytes = 0; const totalBytes = file.size; const stream = file.stream().pipeThrough(new TransformStream({ transform(chunk, controller) { uploadedBytes += chunk.byteLength; const progress = (uploadedBytes / totalBytes) * 100; console.log(`上传进度:${progress.toFixed(2)}%`); controller.enqueue(chunk); } })); const response = await fetch(url, { method: 'POST', body: stream, headers: { 'Content-Type': file.type // 若需FormData,需手动构造multipart/form-data流,实现复杂度更高 } }); return response; }
你可能遗漏的关键信息
Chrome扩展V3并非「不再支持Ajax」——jQuery的Ajax本质是封装了原生XHR,V3只是限制了同步XHR在后台服务worker等场景的使用,异步XHR在大多数上下文(如弹出页、内容脚本)中依然可以正常使用,所以直接用原生XHR是最简单可靠的方案。
内容的提问来源于stack exchange,提问作者L.J.
相关产品推荐
相关产品推荐

