Skip to content

Instantly share code, notes, and snippets.

@spenserhale
Last active February 10, 2022 01:08
Show Gist options
  • Save spenserhale/68b2f52bcae91f0e0ddd1b3411a0cc9a to your computer and use it in GitHub Desktop.
Save spenserhale/68b2f52bcae91f0e0ddd1b3411a0cc9a to your computer and use it in GitHub Desktop.
JavaScript function to trigger file download within the browser.
/**
* Triggers browser to download a file with content.
*
* Accomplishes by creating a temporary a tag that we encode filename and data to and then click on behalf of user.
*
* @example
* browserFileDownload("results.txt","Success Example!");
* @example
* browserFileDownload("example.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><collection><item>1</item></collection>", "application/xml");
*
* @param {string} filename - The filename with extension of the download we want to create and download.
* @param {string} content - The file contents to be encoded for download.
* @param {string} type [type=text/plain] - The type of file encoding (MIME_TYPE).
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
* @param {string} charset [charset=utf-8] - The character set of the file encoding.
*/
function browserFileDownload(filename, content, type = 'text/plain', charset = 'utf-8') {
var link = document.createElement('a');
link.href = 'data:' + type + ';charset=' + charset + ',' + encodeURIComponent(content);
link.download = filename;
link.click();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment