Search code examples
javascriptcodemirror

How do I save the content of the editor, not the whole HTML page?


So far I have an editor made out of a <textarea> with CodeMirror.fromTextArea.

I can write code and it works awesomely, but when I press CTRL+S it shows a dialog to save the HTML page. I'd expect it to instead let me save (download) the code I typed.

I have successfully bound to the save command as follows:

CodeMirror.commands.save = function(editor) {
    console.log("Yay!");
};

and indeed when I hit CTRL+S, I have "Yay!" printed to the console and no dialog is shown.

Now, how do I make a save dialog that saves just the code in the editor instance?


Solution

  • Assuming you initialize CodeMirror like this..

    var editor = CodeMirror.fromTextArea(document.getElementById('...'))...
    

    Then you can adapt the following example function for your purposes:

    function saveTextAsFile() {
      var textToWrite = editor.getValue();
      var textFileAsBlob = new Blob([textToWrite], {
        type: "text/plain;charset=utf-8"
      });
      var fileNameToSaveAs = "myfile.txt";
    
      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();
    }
    

    Good luck!