/** * Triggers a file download dialog in the browser. * @param string content - The file content or a URL. * @param string fileName - The default name for the saved file. * @param string mimeType - The file's MIME type (e.g., 'text/plain'). */ function forceDownload(content, fileName, mimeType = 'application/octet-stream') // 1. Create a Blob from the content if it isn't already a URL const blob = content instanceof Blob ? content : new Blob([content], type: mimeType ); // 2. Create an Object URL representing the blob const url = URL.createObjectURL(blob); // 3. Create a temporary anchor element const link = document.createElement('a'); link.href = url; link.download = fileName; // This attribute forces the download dialog // 4. Append to body, click it, and remove it document.body.appendChild(link); link.click(); document.body.removeChild(link); // 5. Clean up the URL object to free memory setTimeout(() => URL.revokeObjectURL(url), 100); // Example usage: // forceDownload('Hello World!', 'greeting.txt', 'text/plain'); Use code with caution. Copied to clipboard Key Components
: Generates a temporary, unique URL that points to the data stored in memory. javascript force file dialog
: The download attribute only works for same-origin URLs or blob: / data: schemes. If you are trying to force a download from a different domain, you must first fetch the data as a blob then use the function above. /** * Triggers a file download dialog in the browser
: Used to wrap raw data (text, JSON, images) into a file-like object that the browser can process. * @param string mimeType - The file's MIME type (e