This can be achieved using two primary methods: the for client-side data and the Fetch API for retrieving dynamic server responses. Method 1: Client-Side Generation (Blob API)
: Encapsulate your data with a specific MIME type (e.g., text/plain or application/json ).
If the dynamic file is generated on a server (e.g., a PDF report or Excel export), you can use the Fetch API to retrieve it as a blob and then trigger the download using the same anchor-tag method.
: Dynamically create an invisible tag with the download attribute and programmatically click it. javascript
function downloadFile(content, fileName, contentType) { // 1. Create a Blob const a = document.createElement("a"); const file = new Blob([content], { type: contentType }); // 2. Create an Object URL const url = URL.createObjectURL(file); a.href = url; a.download = fileName; // 3. Programmatically click the link to trigger download document.body.appendChild(a); a.click(); // Cleanup setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0); } // Usage Example: downloadFile("Dynamic data generated at " + new Date(), "log.txt", "text/plain"); Use code with caution. Method 2: Server-Generated Files (Fetch API)
In modern web development, downloading a dynamically generated file directly in the browser—without a server-side round trip—is a standard requirement for features like data exports, logs, or user-generated reports.
: This approach allows you to send custom headers (like Authentication tokens) or use POST requests for complex filtering, which standard link clicks cannot do.