How to programmatically trigger a file download when a link or button is clicked.
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:
Blob.<a> element and set its href attribute to a URL created from that Blob.download attribute on the <a> element to specify the filename.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.
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);
}
});