1

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?

Ivan Rubinson
  • 3,001
  • 4
  • 19
  • 48
  • 1
    Maybe this helps: [How to make a browser display a “save as dialog” so the user can save the content of a string to a file on his system?](https://stackoverflow.com/q/11336663/218196) – Felix Kling Jul 12 '18 at 22:12

1 Answers1

3

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!

Pancake
  • 739
  • 1
  • 5
  • 20
  • Nice solution. Works on Firefox, Chrome, and with adblock. I tried on Edge and it works too. I tested on IE11 and it does not work at all. – Ivan Rubinson Jul 13 '18 at 07:07