Search code examples
javascriptdom-eventsinternet-explorer-11dispatchevent

Mouse event for download functionality not working in IE


I am trying to implement a functionality to download a pdf file using javascript. My code is not working in IE 11. Any leads are much appreciated. Below is the code I am using.

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

}


Solution

  • The work around would be, instead of using the mouse event use the function msSaveOrOpenBlob for this functionality. So the final working code will be as below

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