阻止下载出现在 chrome 下载栏上

Stop a download from appearing on chrome download bar

我正在做一个 Chrome 扩展,我正在使用此代码 "catch" 根据要求下载。

chrome.downloads.onCreated.addListener(function(downloadItem) {

});

我想要的是停止下载出现在下载栏上,读取我的扩展中的文件,然后从计算机中删除该文件。

我试过使用 chrome.extensions.download.erase() 和 chrome.browsingData.remove() 但无济于事。

我该怎么做?

在内容脚本中:

document.querySelector("a").addEventListener("click",function(){
 chrome.runtime.sendMessage({action: "download", url: this.href});
});

//您可能应该将选择器限制为您要使用扩展程序下载的特定链接。

在后台页面中:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if(request.action == "download" ){
      //here download via xhr, then read the file as you plan to do 
    }
});

更好的事件是 onDeterminingFilename,因为这发生在下载开始之前:

chrome.downloads.onDeterminingFilename.addListener(function (item) {
    chrome.downloads.cancel(item.id);
});

https://developer.chrome.com/extensions/downloads#event-onDeterminingFilename