如何保存编辑器的内容,而不是整个 HTML 页面?

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

到目前为止,我有一个由 <textarea>CodeMirror.fromTextArea 组成的编辑器。

我可以编写代码,而且效果非常好,但是当我按 CTRL+S 时,它会显示一个对话框来保存 HTML 页面。我希望它能让我保存(下载)我输入的代码。

我已经成功绑定保存命令如下:

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

事实上,当我按下 CTRL+S 时,我已将 "Yay!" 打印到控制台,但未显示任何对话框。

现在,如何创建一个仅保存编辑器实例中代码的保存对话框?

假设您像这样初始化 CodeMirror..

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

然后您可以根据您的目的调整以下示例函数:

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();
}

祝你好运!