'chrome.downloads.download not working from background service worker

I'm trying to create a Chrome Extension that will do some analysis of the page content when the toolbar button is clicked, and then save (i.e. download) the results onto the user's machine. I can get the analysis to work when the button is clicked, but I can't get it to trigger the download.

This is the first time I've written a Chrome Extension, so any help working out why it's not working would be appreciated!

manifest.json

{
  ...
  "permissions": [
    "activeTab",
    "downloads",
    "scripting"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

background.js

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['analysis.js']
  });
});

chrome.runtime.onMessage.addListener((arg, sender, reply) => {
  chrome.downloads.download({
    url: 'data:text/plain,' + arg.text,
    filename: arg.name,
    saveAs: true
  })
});

analysis.js

// Do some analysis here
chrome.runtime.sendMessage({name: "results.txt", text: "ANALYSIS RESULTS HERE"});

When I click the toolbar button, the analysis runs but I don't get a Save dialog nor do any files appear on the disk. What am I doing wrong?



Solution 1:[1]

Not sure if you resolved this yet or if this fix resolves your issue, but I just discovered that the download API only works for me if I have "Ask where to save each file before downloading" unchecked in the general Chrome settings. My workaround for this (and I think it's only with Manifest v3) is to force the download using an anchor tag in the active tab:

const anchor = document.createElement('a');
anchor.href = filedata;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);

Solution 2:[2]

This seems to be a bug in chrome manifest V3. See below for details.
TL&DL, chrome.downloads.download was and still is (as of may 2022) completely broken in manifest V3. On manifest V2, it seems to work.

--
Issue 1246717: chrome.downloads.download never starts, but no errors

chrome.downloads.download never starts, but no errors

https://bugs.chromium.org/p/chromium/issues/detail?id=1246717&

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin
Solution 2 rtfgvb