Skip to content

Instantly share code, notes, and snippets.

@dsetzer
Last active August 31, 2021 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsetzer/210f02101aa394325819405cddbb6f2e to your computer and use it in GitHub Desktop.
Save dsetzer/210f02101aa394325819405cddbb6f2e to your computer and use it in GitHub Desktop.
Initiates a file download from javascript. No longer works from within sandboxed iframes.
function downloadString(data, fileName = 'download.txt', fileType = 'text/plain') {
var blob = new Blob([data], {type: fileType});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else{
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = fileName;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
e.initEvent('click', !0, !1, window, 0, 0, 0, 0, 0, !1, !1, !1, !1, 0, null);
a.dispatchEvent(e);
}
}
// Usage example
// let content = 'a, b, c\n1, 2, 3';
// downLoadString(content, 'content.csv', 'text/csv');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment