Created
July 24, 2014 13:33
-
-
Save catdad/3ecb05702c76c304d192 to your computer and use it in GitHub Desktop.
Download a client-side generated string of text.
This file contains hidden or 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(str){ | |
// get a filename | |
var filename = (prompt('Filename')); | |
if ('Blob' in window) { | |
//create file blob | |
var blob = new Blob([str], { 'type': 'text/plain;charset=utf-8' }); | |
if (window.navigator.msSaveBlob) { | |
//works in IE 10, 11 | |
window.navigator.msSaveBlob(blob, filename); | |
} | |
else { | |
//works in Chrome, Firefox | |
var a = document.createElement('a'); | |
a.href = window.URL.createObjectURL(blob); | |
a.download = filename; | |
//Firefox requires the anchor to be inserted in the document | |
a.style.display = 'none'; | |
document.body.appendChild(a); | |
a.click(); | |
document.body.removeChild(a); | |
} | |
} | |
else { | |
//works in IE 8, 9 | |
if (document.execCommand) { | |
var oWin = window.open('about:blank', '_blank'); | |
oWin.document.write(str); | |
oWin.document.close(); | |
var success = oWin.document.execCommand('SaveAs', true, filename); //filename doesn't seem to work | |
oWin.close(); | |
//TODO this happens when it is not possible AND when the user presses cancel | |
//if (!success) alert('Saving was not successful.'); | |
} | |
//else alert('Saving is not supported in your browser.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment