0

To programmatically trigger a file, located on the server, using JavaScript, here's what I'm currently doing:

HTML

<a id="downloadPDF" href="/my.pdf" download style="display: none;">Download PDF</a>

JavaScript

<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.

GTS Joe
  • 3,612
  • 12
  • 52
  • 94

2 Answers2

1

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');
tarkh
  • 2,424
  • 1
  • 9
  • 12
0

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();
GTS Joe
  • 3,612
  • 12
  • 52
  • 94