首页 > 解决方案 > document.createElement('a').click() 在 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 - 在单击链接被记录到浏览器控制台之前(第一个日志也正确记录了我的数据),但下载没有开始。

我究竟做错了什么?

标签: javascriptfirefox

解决方案


在 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();
    });

代码笔 - http://jsfiddle.net/b40af6rm/


推荐阅读