Reputation: 4182
To programmatically trigger a file, located on the server, using JavaScript, here's what I'm currently doing:
<a id="downloadPDF" href="/my.pdf" download style="display: none;">Download PDF</a>
<script type="text/javascript">
document.getElementById('downloadPDF').click();
</script>
It works, but it feels rather "hackish" to me. Is there a better, more straightforward way of doing it without using HTML and triggering clicks?
Important: No libraries or data URIs. The file should download not open.
Upvotes: 0
Views: 161
Reputation: 4182
Here's my implementation, which I like more since it's cleaner:
document.querySelector( 'body' ).insertAdjacentHTML( 'beforeend', '<a id="downloadPDF" href="/my.pdf" download style="display: none;"></a>' );
document.getElementById( 'downloadPDF' ).click();
Upvotes: 0
Reputation: 2549
This is just extension to method, that you have provided in your question. Differences is that this function do all work in background.
// DL function
const download = function(file) {
// Create a tag
const a = document.createElement('a');
// Set href
a.href = file;
// Set file name
a.download = file.substr(file.lastIndexOf('/') + 1);
// Append tag to body
document.body.appendChild(a);
// Click it
a.click();
// Remove
document.body.removeChild(a);
}
// Do download
download('https://file-examples-com.github.io/uploads/2017/02/zip_2MB.zip');
Upvotes: 1