Created
February 2, 2021 20:16
-
-
Save tomowarkar/7390b4c0d69b09557d401d1ec04d6c45 to your computer and use it in GitHub Desktop.
文字列をファイルとしてダウンロードする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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Download Test</title> | |
</head> | |
<div> | |
<textarea id="input-text" rows="10" cols="60">Download Test</textarea> | |
<button id="btn">download</button> | |
</div> | |
<script> | |
let inputText = document.getElementById("input-text") | |
let btn = document.getElementById("btn") | |
downloadText = (text, filename) => { | |
let blob = new Blob([text], {type: 'text/plain'}); | |
let url = URL.createObjectURL(blob); | |
let a = document.createElement("a"); | |
document.body.appendChild(a); | |
a.download = filename; | |
a.href = url; | |
a.click(); | |
a.remove(); | |
URL.revokeObjectURL(url); | |
} | |
btnClicked = (ev) => { | |
console.log("btn clicked") | |
downloadText(inputText.value, "example.txt") | |
} | |
btn.addEventListener('click', btnClicked) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment