Skip to content
Advertisement

Trigger download immediately after document ready

I am trying to download a file immediately after a page has been loaded by triggering an a link.

...
<a id="download" href="/some/link/to/download.pdf"></a>

<script>
  $(document).ready(function(){
    $('#download').trigger("click");
  });

</script>

But this isn’t working for some reason. Am I doing something wrong?

Advertisement

Answer

You can dynamically create and click a link when the page loads – simply add this to the page markup:

<script>
  window.onload = function() {
    var a = document.createElement("a");
    a.href = "/some/link/to/download.pdf";
    a.download = true;
    a.click();
  };
</script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement