How do I trigger a download when I click a link or button?

Updated:

Related pages: Button, Link

You can trigger a download in JavaScript by programmatically creating and clicking an anchor (<a>) element. This approach doesn’t require adding the element to the DOM; it just simulates a user click to start the download.

Here’s how it works:

  1. Add an event listener to the element that will handle the click.
  2. Fetch the content you want to save.
  3. Convert your payload into a Blob.
  4. Create a virtual <a> element and set its href attribute to a URL created from that Blob.
  5. Set the download attribute on the <a> element to specify the filename.
  6. Trigger a click programmatically on the anchor tag.

We admit this approach may seem a little odd, but it is a little more straightforward and stable than the old document.execCommand('SaveAs') approach and will be what we recommend until we can use window.showSaveFilePicker.

It is your responsibility to ensure you have permission to download the files you seek to provide to the user. This means CORS policies may need to be updated to allow for the payload to be fetched from your feature's URL.

document.querySelector("#my-element").addEventListener("click", async () => {
  const url = "https://tecton.q2developer.com/examples/headshot.jpg";
  const filename = "headshot.jpg";
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const blobUrl = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = blobUrl;
    link.download = filename;
    link.click();

    URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.error("Download failed:", error);
  }
});