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:
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
.
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);
}
});