Created
March 18, 2023 13:05
-
-
Save karlkori/227f1fe6874612ca174849f699aeef9e to your computer and use it in GitHub Desktop.
saveTextAsFile
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 saveTextAsFile(textToWrite, fileNameToSaveAs, fileType) { | |
| let textFileAsBlob = new Blob([textToWrite], { type: fileType }); | |
| let downloadLink = document.createElement('a'); | |
| downloadLink.download = fileNameToSaveAs; | |
| downloadLink.innerHTML = 'Download File'; | |
| if (window.webkitURL != null) { | |
| downloadLink.href = window.webkitURL.createObjectURL( | |
| textFileAsBlob | |
| ); | |
| } else { | |
| downloadLink.href = window.URL.createObjectURL(textFileAsBlob); | |
| downloadLink.style.display = 'none'; | |
| document.body.appendChild(downloadLink); | |
| } | |
| downloadLink.click(); | |
| } | |
| saveTextAsFile('{"hello": "world"}', 'hello.json', 'application/json'); | |
| saveTextAsFile('Hello World!', 'hello.txt', 'text/plain'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment