Created
June 9, 2018 16:00
-
-
Save kocisov/30f984e7a64653fb59058f69a96c90bc to your computer and use it in GitHub Desktop.
Download in JavaScript
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 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