如何使用Firefox WebExtension以编程方式下载在该文件上创建的文件? [英] How do I programmatically download a file created on the file with a Firefox WebExtension?

查看:68
本文介绍了如何使用Firefox WebExtension以编程方式下载在该文件上创建的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是Javascript代码:

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 

所有行似乎执行正常,但是没有下载文件(我在a.click()之后放置了console.log()).

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

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

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

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

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

推荐答案

一种方法是将事件监听器添加到a标签.

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

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

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

因此,此代码可以按原样在firefox,chrome和Opera网络扩展中运行.

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

这篇关于如何使用Firefox WebExtension以编程方式下载在该文件上创建的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆