简体   繁体   中英

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 (ie 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?

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);

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&

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM