How do I programmatically download a file created on the file with a Firefox WebExtension?

与世无争的帅哥 提交于 2019-12-23 10:49:30

问题


I am trying to port a Chrome Extension that programmatically creates and downloads a file to a Firefox WebExtension, using Firefox 45.0.1.

This is the Javascript code:

  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 

All lines seem to execute fine, but no file is downloaded (I put a console.log() after the a.click()).

As of now there is no chrome.downloads API in Firefox WebExtensions.

Is there any incompatibility with Firefox in the code above? Is there any other alternative to programmatically download a file using a Firefox WebExtension?


回答1:


One way to do this, would be to add an event listener to the a tag.

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

Notice that I use the downloadVidWithChromeApi function like so, to check if chrome.downloads is supported.

Therefore this code can run in both firefox, chrome, AND opera web extensions AS IS.



来源:https://stackoverflow.com/questions/36139329/how-do-i-programmatically-download-a-file-created-on-the-file-with-a-firefox-web

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!