Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  37] [ 3]  / answers: 1 / hits: 37699  / 8 Years ago, fri, july 22, 2016, 12:00:00

I'm trying to make the browser download a pdf file received from an ajax response.



Inspired by Download pdf file using jquery ajax I simulate a click/download event like this:



    var req = new XMLHttpRequest();
req.open(POST, /servicepath/Method?ids= + ids, true);
req.responseType = blob;
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = PdfName- + new Date().getTime() + .pdf;
link.click();
}
};
req.send();


Unfortunately this only works in Chrome, but not Firefox + IE. Nothing happens when I try to trigger it in the last two browsers.



The script and markup is placed inside an iframe due to inheritance from an CMS, but I'm not sure if that has any influence a.



Any idea on how to optimize it for all modern browsers?


More From » jquery

 Answers
3

Any idea on how to optimize it for all modern browsers?




Yes, I can give you a solution tested on windows 10 with IE11, Firefox 47 and Chrome 52. Nothing for Microsoft Edge at the moment.



At the beginning you need to distinguish if you are on IE or the other two browsers. This because on IE11 you can use:



window.navigator.msSaveBlob(req.response, PdfName- + new Date().getTime() + .pdf);


For the other two browsers your code works on Chrome but not on Firefox because you did not append the element to the document body.



So the corrected code is:



var req = new XMLHttpRequest();
req.open(POST, /servicepath/Method?ids= + ids, true);
req.responseType = blob;
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {

// test for IE

if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, PdfName- + new Date().getTime() + .pdf);
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = PdfName- + new Date().getTime() + .pdf;

// append the link to the document body

document.body.appendChild(link);

link.click();
}
}
};
req.send();



[#61286] Tuesday, July 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamila

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;