Trigger download immediately after document ready

Tags: ,



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?

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>


Source: stackoverflow