Passing FormData/File Object from content script to background script in chrome extension with Manifest V3

939 views
Skip to first unread message

Koushik R

unread,
Aug 11, 2021, 12:13:11 AM8/11/21
to Chromium Extensions

Hi Team,

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 uses JSON Serialization and what I receive in my `background.js` is an empty object. Refer to the snippet I attached in the StackOverflow here.

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.

Simeon Vincent

unread,
Aug 13, 2021, 12:25:11 PM8/13/21
to Koushik R, Chromium Extensions
It would help if you could share an example extension to see where exactly things are breaking down for you.

For better or worse, different JS execution environments cannot directly access each other's JS and the extension message passing system in Chrome is built on JSON serialization. To work around that you'll likely need to do something like what is described in your first StackOverflow link.

Simeon - @dotproto
Chrome Extensions DevRel


--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/6bac2af9-dde4-42c5-911e-014c5d6c9f3bn%40chromium.org.

Cuyler Stuwe

unread,
Aug 13, 2021, 5:02:02 PM8/13/21
to Chromium Extensions, Simeon Vincent, Chromium Extensions, Koushik R
If you own the backend, and enabling CORS makes sense, then you can definitely do that to enable data transfer.
Example -- This content.js file, when running on Twitter, leads to this console log:

Screen Shot 2021-08-13 at 2.00.32 PM.png

Now, it's true that you might not be able to bypass CORS restrictions within a content script, but this does open you up to normal workarounds that a regular frontend might use (e.g., using a CORS proxy).

Something to consider.
Reply all
Reply to author
Forward
0 new messages