下载功能的鼠标事件在 IE 中不起作用

Mouse event for download functionality not working in IE

我正在尝试使用 javascript 实现下载 pdf 文件的功能。我的代码在 IE 11 中不起作用。非常感谢任何线索。下面是我正在使用的代码。

saveByteArray: function(reportName, byte) {
     
var bytes = new Uint8Array(byte);
var blob = new Blob([bytes], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));

}

MouseEvent 构造函数(new MouseEvent()is not supported by IE 11

世界上有多种 polyfill,例如 this one from the Mozilla docs, but I generally find it easier and more comprehensive to use something like Babel 可以自动生成和使用那种 polyfill,而无需为 IE 不支持的每一个东西明确搜索和定义它们(这很多)。

解决方法是,不使用鼠标事件,而是使用函数 msSaveOrOpenBlob 来实现此功能。所以最终的工作代码如下

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        var bytes = new Uint8Array(byte);
        var blob = new Blob([bytes], {type: "application/pdf"});
        window.navigator.msSaveOrOpenBlob(blob, reportName+".pdf");
        
    } else {
     
        var bytes = new Uint8Array(byte);
        var blob = new Blob([bytes], {type: "application/pdf"});
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        var fileName = reportName;
        link.download = fileName;
        link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
    }

您不需要新的 MouseEvent 来进行简单的点击(您不需要手动指定 screenXscreenY 等)。

你可以直接使用IE11支持的link.click()https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

尝试以下操作:

var bytes = new Uint8Array(byte);
var blob = new Blob([bytes], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click()

(另请注意,IE11 也不支持 'download' 属性:https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/download,我现在没有 IE11,但我认为它只是忽略)