我正在构建一个 chrome 扩展,在其中我从用户那里获取一个文件作为输入,并将其传递给我的 background.js(在清单 v3 的情况下为服务工作者)以将其保存到我的后端。由于内容脚本阻止了跨域请求,因此我必须将其传递给我background.js
并使用 FETCH API 来保存文件。当我将FormData
orFile
对象传递给chrome.runtime.sendMessage
API 时,它使用 JSON 序列化,而我收到的background.js
是一个空对象。请参阅以下代码段。
//content-script.js
attachFile(event) {
let file = event.target.files[0];
// file has `File` object uploaded by the user with required contents.
chrome.runtime.sendMessage({ message: 'saveAttachment', attachment: file });
}
//background.js
chrome.runtime.onMessage.addListener((request, sender) => {
if (request.message === 'saveAttachment') {
let file = request.attachment; //here the value will be a plain object {}
}
});
即使我们FormData
从内容脚本传递,也会发生同样的情况。
我参考了旧 StackOverflow 问题建议的多种解决方案,使用URL.createObjectURL(myfile);
URL 并将其传递给我background.js
并获取相同的文件。而 FETCH API 不支持获取 blob URL,并且这里XMLHttpRequest
推荐的 service worker 也不支持。有人可以帮我解决这个问题吗?我被这种行为挡住了。