JavaScript Template for Writing to a File through a Blob
The Blob object is a built-in JavaScript feature that allows you to create file-like objects of immutable raw data. Using a Blob, you can easily generate text files directly in the browser. Here's how to use it:
- Create a Blob object containing the data you want to write to a text file.
- Use the
URL.createObjectURL()method to create a downloadable link. - Trigger the file download automatically when the user clicks a button.
The (relevant) code:
<div>
<textarea id="textData" rows="6" cols="50" placeholder="Enter text to save"></textarea><br/><br/>
<textarea id="fileName" rows="1" cols="50" placeholder="FILENAME.txt"></textarea><br/><br/>
<button onclick="saveTextFromIdToId('textData', 'fileName')">Download Text File using saveTextFromIdToId(txt,file)</button>
</div>
<script>
function saveText(text, fileName="saved.txt") {
var blob = new Blob([text], { type: 'text/plain' });
var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
function saveTextFromIdToId(textareaId, fileNameId) {
var text = document.getElementById(textareaId).value;
var fileName = document.getElementById(fileNameId).value;
saveText(text,fileName);
}
(You may of course change the identifiers, forego embedding your textarea and button in a div element, etc.)