22

Could someone help me save the contents of a HTML5 textArea to file, preferably using JavaScript?

<textarea id="textArea">
   Notes here...
</textarea>
<button type="button" value="save"> Save</button>
1

4 Answers 4

29

That should do it.

function saveTextAsFile() {
  var textToWrite = document.getElementById('textArea').innerHTML;
  var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
  var fileNameToSaveAs = "file.txt"; //filename.extension

  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "Download File";
  if (window.webkitURL != null) {
    // Chrome allows the link to be clicked without actually adding it to the DOM.
    downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  } else {
    // Firefox requires the link to be added to the DOM before it can be clicked.
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
  }

  downloadLink.click();
}

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);

function destroyClickedElement(event) {
  // remove the link from the DOM
  document.body.removeChild(event.target);
}
#textArea {
  display: block;
  width: 100%;
}
<textarea id="textArea" rows="3">
   Notes here...
</textarea>
<button type="button" value="save" id="save">Save</button>

JSFiddle

3
  • This didn't work for me, the solution was to call the function with button onclick cf stackoverflow.com/a/41965468/3154274
    – MagTun
    Jan 31, 2017 at 19:06
  • textToWrite is a textarea's innerHTML, not the textarea itself. I will add an edit. Thanks for the solution though. Mar 9, 2018 at 13:45
  • 1
    Thanks a lot for the solution! It helped me a lot. Just one point about the content saved in the file: I think it's wrong because we shouldn't read the innerHTML property of the textarea but the value property instead. Sep 23, 2020 at 22:10
13

A simplified version of the code in the answers:

function download(){
    var text = document.getElementById("my-textarea").value;
    text = text.replace(/\n/g, "\r\n"); // To retain the Line breaks.
    var blob = new Blob([text], { type: "text/plain"});
    var anchor = document.createElement("a");
    anchor.download = "my-filename.txt";
    anchor.href = window.URL.createObjectURL(blob);
    anchor.target ="_blank";
    anchor.style.display = "none"; // just to be safe!
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
 }

and the html:

<textarea id="my-textarea">
   Notes here...
</textarea>
<button type="button" onclick="download()">Save</button>
4
  • I like the simplicity. However newline characters do not appear in the downloaded file - all text is run together on one line. Feb 25, 2018 at 2:37
  • 1
    I found a fix for your code at this question: stackoverflow.com/questions/19190331/… Feb 25, 2018 at 2:46
  • 3
    The fix would be to add this line before your blob declaration: text = text.replace(/\n/g, "\r\n"); Feb 25, 2018 at 2:46
  • Thanks for summarising. This works nicely but doesn't work on iOS which just displays the blob in a new browser window. Any suggestions on how to get it to work properly and take the suggested filename? Aug 20, 2021 at 16:03
2

I tested engincancan's answer, and it was almost there, but not quite. First of all, the file format for "ecc.plist" was not recognizable anywhere. Second of all, in order for the code to work on the desktop in Safari, Chrome, and Firefox, you have to use an existing anchor tag and not create one (document.createElement('a')). The destroyClickedElement approach only works in Chrome, because it is so forgiving and lenient. And, in order for the download to work in Firefox, you have to have document.body.appendChild(downloadLink.download);

I also had wanted to save my local storage text to a file for download and the code works on desktop for Safari, Chrome and Firefox on Mac. However, I think it is impossible in iOS to save the Blob() anywhere with Chrome or Firefox. It does work, interestingly enough in Safari. For example, I can save the text file to my Wunderlist app. Here is the link my repo on Github: The Cat Whisperer on Github gh-pages

Here is the JavaScript code:

const fileDownloadButton = document.getElementById('save');
function localStorageToFile() {
    const csv = JSON.stringify(localStorage['autosave']);
    const csvAsBlob = new Blob([csv], {type: 'text/plain'});
    const fileNameToSaveAs = 'local-storage.txt';
    const downloadLink = document.getElementById('save');
    downloadLink.download = fileNameToSaveAs;
    if (window.URL !== null) {
        // Chrome allows the link to be clicked without actually adding it to the DOM
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
    } else {
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
        downloadLink.style.display = 'none';
        // add .download so works in Firefox desktop.
        document.body.appendChild(downloadLink.download);
    }
    downloadLink.click();
}
// file download button event listener
fileDownloadButton.addEventListener('click', localStorageToFile);      
-1
<textarea id = "textArea">
    Notes here...
</textarea>

<button onclick="savetextarea()" type="button">Save</button>

<script>
    function savetextarea(){
        var txt = document.getElementById("textArea").value;
        document.getElementById("saveinput").value = txt;
        document.forms["aForm"].submit();
    }
</script>

<form action="savecontent" name="aForm">
    <input id="saveinput" type="hidden" name="filecontent" value="">
</form>
1
  • 3
    This will only work if there's something on server side handling the actual saving of the file... so it does not answer the question
    – MrAn3
    Oct 9, 2016 at 22:06

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.