如何使用Firefox WebExtension以编程方式下载在该文件上创建的文件?

Pep*_*Pep 5 firefox-addon-webextensions

我正在尝试移植一个Chrome扩展程序,该程序可以使用Firefox 45.0.1以编程方式创建文件并将其下载到Firefox WebExtension。

这是Javascript代码:

  text = '{"greeting":"Hello, World!"}';
  var a = document.createElement('a');
  var file = new Blob([text], {type: 'text/json'});
  a.href = URL.createObjectURL(file);
  a.download = 'hello.world';   // Filename  
  a.click();                    // Trigger download 
Run Code Online (Sandbox Code Playgroud)

所有行似乎都可以正常执行,但是没有文件下载(我在console.log()后面放了一个a.click())。

截至目前,Firefox WebExtensions中还没有chrome.downloads API。

上面的代码是否与Firefox不兼容?除了使用Firefox WebExtension以编程方式下载文件之外,还有其他选择吗?

Sud*_*Plz 1

实现此目的的一种方法是将事件侦听器添加到 a 标记。

text = '{"greeting":"Hello, World!"}';
var a = document.createElement('a');
var file = new Blob([text], {type: 'text/json'});
a.href = URL.createObjectURL(file);
a.download = 'hello.world';   // Filename  
a.addEventListener('click', dlLinkClicked);


function dlLinkClicked(e){
    var link = e.currentTarget.href;
    var filename = e.currentTarget.download;

    /*downloadVidWithChromeApi downloads using the chrome download API, 
    otherwise returns false and starts downloading the file 
    using the html5 download - you don't have to do anything else*/

    if(downloadVidWithChromeApi(link, filename)){
        e.preventDefault();
    }
}

function downloadVidWithChromeApi(link, fileName){
    if(chrome.downloads && chrome.downloads.download){
        chrome.downloads.download({
            url: link,
            saveAs: false,
            filename: fileName // Optional
        });
        return true;
    }else{
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用downloadVidWithChromeApi这样的函数来检查是否支持 chrome.downloads。

因此,此代码可以在 Firefox、Chrome 和 Opera Web 扩展中按原样运行。