Last active
August 31, 2021 00:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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