Created
October 28, 2020 02:11
-
-
Save ccondry/28f35ab9c50087f6af485d894262f4f3 to your computer and use it in GitHub Desktop.
make the browser download a plaintext file instead of rendering it
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
<a href="data:text/plain;charset=utf-8,encodeURIComponent(text)" download="all.zip"> | |
function downloadText (text) { | |
// create anchor | |
element = document.createElement('a') | |
// set the href to URI-encoded plaintext data | |
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)) | |
// set the filename the browser will use as default when starting download | |
element.setAttribute('download', 'myfile.txt') | |
// keep the element hidden when placed into body | |
element.style.display = 'none' | |
// place this element into the body | |
document.body.appendChild(element) | |
// click the new link element to start the download | |
element.click() | |
// remove the new link element | |
document.body.removeChild(element) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment