firefox-addon-webextensions - 如何以编程方式下载使用 Firefox WebExtension 创建的文件?

标签 firefox-addon-webextensions

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

这是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 

所有行似乎都执行得很好,但没有下载文件(我在 console.log() 后面放了一个 a.click() )。

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

上面的代码中是否有与 Firefox 不兼容的地方?是否有其他替代方法可以使用 Firefox WebExtension 以编程方式下载文件?

最佳答案

一种方法是向 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;
    }
}

请注意,我使用了 downloadVidWithChromeApi像这样的功能,检查是否支持 chrome.downloads。

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

关于firefox-addon-webextensions - 如何以编程方式下载使用 Firefox WebExtension 创建的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139329/

相关文章:

javascript - Firefox WebExtension 内的 CORS 获取出现 TypeError

javascript - 注入(inject)CSS时立竿见影

google-chrome-extension - 在 Chrome 网络扩展程序中访问和修改 CSSrules

firefox-addon-webextensions - 页面加载时显示 Firefox WebExtension 页面操作

javascript - 无法从后台脚本接收选项卡上的消息

javascript - 读取 list : Error processing options_page: An unexpected property was found in the WebExtension

javascript - 从 Firefox 插件(Webextension API)修改网页 : how to access the elements properly?

javascript - 单击按钮删除 Cookie - Web 扩展 API

google-chrome-extension - 使用 chrome.* 或 browser.* 的 Firefox/Chrome/MS Edge 扩展

javascript - Chrome扩展能否动态添加JS文件到本地扩展目录?用户上传还是从网络保存?