Wed, 09 Apr 2025
Universal JS Download Modal Triggering Code
This handy javascript programming takes two incoming arguments, and invokes the download dialogue modal for any text supplied to it. Just provide it with a fileName (to be used when saving the "file"), and fileContents, and see for yourself.
Highlight and copy the Javascript code below, starting with the "function" line, and ending with the very last right-squiggly-bracket that's followed by a semi-colon.
######################################################### JS Programming Below ######################################################### function createAndDownloadFile(fileName, fileContent) {
// Create a Blob from the content (assuming it's text data) const blob = new Blob([fileContent], { type: 'text/plain' });
// Create an object URL for the Blob const url = URL.createObjectURL(blob);
// Create an anchor element const a = document.createElement('a');
// Set the download attribute with the specified file name a.download = fileName;
// Set the href attribute to the Blob URL a.href = url;
// Append the anchor element to the document body (required for Firefox) document.body.appendChild(a);
// Trigger a click on the anchor element to start the download a.click();
// Clean up by removing the anchor element document.body.removeChild(a);
// Optionally, release the object URL after use to free memory URL.revokeObjectURL(url); }; ######################################################### JS Programming Above #########################################################
posted at: 9:54am on 09-Apr-2025 path: /Programming/Javascript | permalink
comment...
|
|