Auto File Download on Page Navigation in JavaScript

You might have seen scenarios where a file automatically gets downloaded as soon as you visit a specific page.

Let’s see on how to trigger an automatic file download when a user navigates to a new page using JavaScript.

Setting Up the Current Page

First, let's set up our current page with a link to the new page. We will use JavaScript to handle the link click and redirect to the new page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Current Page</title>
  </head>
  <body>
    <h1>Welcome to the Current Page</h1>
    <a href="download.html" id="download-link">Go to Download Page</a>

    <script>
      // JavaScript to handle the anchor click and redirection
      document
        .getElementById("download-link")
        .addEventListener("click", function (event) {
          event.preventDefault(); // Prevent the default anchor behavior
          window.location.href = "download.html"; // Redirect to the new page
        });
    </script>
  </body>
</html>

Setting Up the New Page

Next, let's set up our new page. This page will automatically trigger a download of the specified file when the page loads. It also provides a manual download link in case the automatic download doesn't work.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Download Page</title>
  </head>
  <body>
    <h1>Welcome to the Download Page</h1>
    <p>
      Your download should start automatically. If not,
      <a id="manual-download" href="#">click here</a> to start the download.
    </p>

    <script>
      // Function to trigger the download
      function triggerDownload(url) {
        // Create an invisible anchor element
        const a = document.createElement("a");
        a.href = url;
        a.download = ""; // Optional: You can set a default filename here
        a.style.display = "none";

        // Append the anchor to the body
        document.body.appendChild(a);

        // Programmatically click the anchor to trigger the download
        a.click();

        // Remove the anchor from the document
        document.body.removeChild(a);
      }

      // Automatically trigger the download on page load
      document.addEventListener("DOMContentLoaded", function () {
        triggerDownload("<https://example.com/path/to/your/file.zip>"); // Replace with your file URL
      });

      // Handle manual download link click
      document
        .getElementById("manual-download")
        .addEventListener("click", function (event) {
          event.preventDefault();
          triggerDownload("<https://example.com/path/to/your/file.zip>"); // Replace with your file URL
        });
    </script>
  </body>
</html>

The above code uses the function, triggerDownload, which creates an invisible hyperlink (<a>) element, sets its href attribute to the URL of the file to be downloaded, and triggers a click event on it to start the download.

This function is called automatically when the page finishes loading, thanks to the DOMContentLoaded event listener.

There's also a manual download link that users can click if the automatic download doesn't start. When this link is clicked, the default action is prevented and the triggerDownload function is called, initiating the download.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda