Skip to content

Instantly share code, notes, and snippets.

@kocisov
Created June 9, 2018 16:00
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 kocisov/30f984e7a64653fb59058f69a96c90bc to your computer and use it in GitHub Desktop.
Save kocisov/30f984e7a64653fb59058f69a96c90bc to your computer and use it in GitHub Desktop.
Download in JavaScript
function download(filename, text) {
// create link element
const element = document.createElement('a')
// set link href to our text
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`)
// set attribute download
element.setAttribute('download', filename)
// make element invisible
element.style.display = 'none'
// add element to the DOM
document.body.appendChild(element)
// simulate click
element.click()
// and remove element from the DOM
document.body.removeChild(element)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment