Reputation: 15
I've got a page with a button that allows to download a XML file by address. At the beginning the js code connected to the button was:
function downloadURI(uri, name) {
window.location = uri;
}
But all browsers opened the file instead of download it. Then I've tried with this code:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
It works for IE, Edge, Opera and Chrome, but not on firefox. Can anyone help me solve it?
Upvotes: 0
Views: 3772
Reputation: 1074268
Firefox doesn't like clicks on links that aren't in the document. So append the link to document.body
(or whatever) prior to the link.click
call (and then remove it afterward, perhaps after a small setTimeout
delay), e.g.:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
setTimeout(function() {
documet.body.removeChild(link);
}, 50);
}
If that doesn't work in your setup, the way I've done this reliably is to make what the user clicks a link rather than a button, and have the link target a hidden iframe
by name, and have the response to the link request contain the Content-Disposition: attachment; filename=foo
header, which tells the browser to download rather than open.
Upvotes: 1