Skip to content

Instantly share code, notes, and snippets.

@ccondry
Created October 28, 2020 02:11
Show Gist options
  • Save ccondry/28f35ab9c50087f6af485d894262f4f3 to your computer and use it in GitHub Desktop.
Save ccondry/28f35ab9c50087f6af485d894262f4f3 to your computer and use it in GitHub Desktop.
make the browser download a plaintext file instead of rendering it
<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