I'm building a chrome extension where I get a file as input from the user and pass it to my background.js (service worker in case of manifest v3) to save it to my backend. Since making cross-origin requests are blocked from content scripts I have to pass the same to my background.js
and use FETCH API to save the file. When I pass the FormData
or File
Object to the chrome.runtime.sendMessage
API it uses JSON Serialization and what I receive in my background.js
is an empty object. Refer to the below snippet.
//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 {}
}
});
The same happens even when we pass the FormData
from the content script.
I referred to multiple solutions suggested by the old StackOverflow questions, to use URL.createObjectURL(myfile);
and pass the URL to my background.js
and fetch the same file. Whereas FETCH API does not support blob URL to fetch and also XMLHttpRequest
is not supported in service worker as recommended here. Can someone help me in solving this? Am so blocked with this behaviour.