Export to CSV from a v3 extension

493 views
Skip to first unread message

Martin Sonesson [C]

unread,
Jun 28, 2023, 6:49:14 AM6/28/23
to Chromium Extensions
Hello! I am currently migrating an extension from v2 to v3. I have some problem with the following snippet that is supposed to take some data and export it to CSV, using the downloads API which then downloads the exported csv-file to the users computer. Here's the snippet:

const text = rows.map(e => e.join(",")).join("\n");
var blob = new Blob([text], { type: "text/csv;charset=utf-8" });
chrome.downloads.download({
'url': URL.createObjectURL(blob),
'filename': 'export.csv',
});

The "rows" variable is basically an array of arrays that looks a bit like this:

[
  ['title1', 'title2', 'title3'],
  ['data1', 'data2', 'data3']
  etc etc.....
]

This works great in the v2 version, but for v3 it seems I can't use "URL.createObjectURL" in a service worker. Any idea how I can do this in v3?

Oliver Dunk

unread,
Jun 28, 2023, 6:53:29 AM6/28/23
to Martin Sonesson [C], Chromium Extensions
Hey!

The easiest option for this would be to use a data URI:

chrome.downloads.download({
  url: 'data:text/plain;base64,' + btoa(text),
  filename: 'fileName.txt'
});

Alternatively, if there's a reason you're particularly keen to use an object URL, you could open an offscreen document to create it and then pass it back to the service worker to perform the download: https://developer.chrome.com/docs/extensions/reference/offscreen/

Hope that helps!
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB


--
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/80b2a40b-c29c-468a-8171-b4e3c34c390en%40chromium.org.

Martin Sonesson [C]

unread,
Jun 28, 2023, 6:59:48 AM6/28/23
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Martin Sonesson [C]
Thanks for the answer Oliver.

Your solution works good for saving to txt-file, but I want to convert to a csv file.

I tried this snippet:
let downloading = chrome.downloads.download({
'url': 'data:text/plain;base64,' + btoa(text),
'filename': 'export.csv'
});

But it seems to always become a txt-file despite my filename having the csv file extension declared.

Oliver Dunk

unread,
Jun 28, 2023, 7:02:55 AM6/28/23
to Martin Sonesson [C], Chromium Extensions
Can you try changing text/plain to text/csv?


Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Martin Sonesson [C]

unread,
Jun 28, 2023, 7:18:30 AM6/28/23
to Oliver Dunk, Chromium Extensions

Vũ Thảo Nguyên, thanks a lot! Your method worked great


Reply all
Reply to author
Forward
0 new messages