javascript - 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 - 在单击链接被记录到浏览器控制台之前(第一个日志也正确记录了我的数据),但下载没有开始。
我究竟做错了什么?
解决方案
在 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();
});
推荐阅读
- google-cloud-platform - Google Cloud Functions 的身份验证方面有哪些?
- c# - 在使用 IN 的内部联接中使用 VARCHAR(Max)(这实际上是一个字符串 [])
- javascript - 如何为内容可编辑元素上的特定单词着色?
- elasticsearch - 日志没有从 logstash 推送到 elasticsearch
- python - 将纬度和经度转换为具有指定参考点的给定平面的 X 和 Y 坐标
- dynamics-crm - 当 Dynamics 365 嵌入 Microsoft Teams 应用程序时,如何在 Dynamics 365 中限定潜在客户?
- javascript - 框内可调整大小的范围输入滑块
- python - for循环后脚本不恢复
- c# - 从 Label-ScrollView -Xamarin Forms 中获取价值
- android - 出现键盘时按钮向上移动