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}));
}
You don't need a new MouseEvent for a simple click (where you don't manually specify screenX, screenY etc).
You can just use link.click() which is supported in IE11: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
Try the following:
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()
(Also note that the 'download' property is not supported in IE11 either: https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/download, I don't have IE11 right now, but I think it'll just be ignored)
The MouseEvent constructor (new MouseEvent()) is not supported by IE 11.
There are multiple polyfills out in the world, like this one from the Mozilla docs, but I generally find it easier and more comprehensive to use something like Babel to automatically generate and use that kind of polyfill without having to explicitly search out and define them for each and every thing IE doesn't support (which is a lot).
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}));
}