document.createElement('a')。click()在Firefox中不起作用

时间:2019-03-14 12:47:27

标签: javascript firefox

我有一个函数可以从我的API中检索arraybuffer数据,在页面上创建一个临时锚,然后单击它以下载文件。

该功能可以在Chrome浏览器中正常工作。

@action
  async loadVoucher(id, fiscalId) {
    const pdf = await this.httpClient.get(...);

    console.log("load Voucher: ", pdf);

    const blob = new Blob([pdf.data], { type: "application/pdf" });
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "Dossier_" + new Date() + ".pdf";

    console.log("before link click");

    link.click();
    link.remove();
  }

@action装饰器来自mobx。在firefox中,第二个console.log-在单击链接记录到浏览器控制台之前(第一个日志也正确记录了我的数据),但是下载没有开始。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

在Firefox中,您需要将创建的元素添加到DOM中,它将起作用:

<div class="button" id="test">Create File</div>

    $('body').on('click', '#test', function(event) {
        var link = document.createElement('a');
        // Add the element to the DOM
        document.body.appendChild(link);
        link.setAttribute("type", "hidden"); // make it hidden if needed
        link.download = 'test.xls';
        link.href = 'data:application/vnd.ms-excel;utf-8,test';
        link.click();
    });

codepen-http://jsfiddle.net/b40af6rm/