Limpar e redefinir um editor de texto rico com JavaScript

Limpar e redefinir um editor de texto rico com JavaScript

Limpe o conteúdo, restaure o documento inicial e trate a redefinição do formulário sem perder rascunhos por acidente.

Limpar e redefinir são ações diferentes

Limpar substitui o documento por um valor vazio. Redefinir restaura um documento inicial definido. Nenhuma dessas ações exclui registros do banco nem imagens enviadas. Mantenha a mesma instância e não substitua seu DOM com innerHTML.

Execute o exemplo completo

Sirva os arquivos do editor pela aplicação. O exemplo confirma ações destrutivas, preserva alterações ao cancelar e lê o HTML atual no envio. Nenhuma requisição é enviada. O formulário nativo restaura o título; o documento é restaurado explicitamente.

<link rel="stylesheet" href="/richtexteditor/rte_theme_default.css">
<script src="/richtexteditor/rte.js"></script>
<script src="/richtexteditor/plugins/all_plugins.js"></script>
<style>body{font:16px/1.6 system-ui;max-width:960px;margin:24px auto;padding:0 16px}button,input{min-height:44px;box-sizing:border-box}button{padding:8px 16px} .actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:16px}</style>
<h1>Clear or reset a rich text editor</h1>
<form id="note-form">
  <label>Title <input name="title" value="Project notes"></label>
  <div style="max-width:100%;overflow-x:auto"><div id="editor"></div></div>
  <div class="actions">
    <button type="button" id="clear">Clear content</button>
    <button type="reset">Restore initial form</button>
    <button type="submit">Check HTML</button>
  </div>
  <p id="status" role="status" aria-live="polite"></p>
</form>
<script>
const initialHTML = "<h2>Project notes</h2><p>Keep <strong>this starting document</strong>.</p>";
const editor = new RichTextEditor("#editor", { toolbar: "full", height: "320px" });
const form = document.getElementById("note-form");
const status = document.getElementById("status");
editor.setHTMLCode(initialHTML);
document.getElementById("clear").addEventListener("click", () => {
  if (!window.confirm("Clear the current document? This demo has no saved backup.")) return;
  editor.setHTMLCode("");
  status.textContent = "Content cleared. Title unchanged. Nothing was saved.";
});
form.addEventListener("reset", event => {
  if (!window.confirm("Restore the initial title and document?")) {
    event.preventDefault();
    return;
  }
  // Native reset restores ordinary fields; explicitly restore the editor.
  editor.setHTMLCode(initialHTML);
  status.textContent = "Initial form restored. Nothing was saved.";
});
form.addEventListener("submit", event => {
  event.preventDefault();
  // Read live editor data, not the original markup or a stale hidden field.
  const html = editor.getHTMLCode();
  status.textContent = "Current HTML: " + html.length + " UTF-16 units. No request sent.";
});
window.resetDemo = { editor, initialHTML };
</script>

Coordene a redefinição com o salvamento automático

O salvamento automático pode tratar a redefinição como uma edição normal. Decida entre salvar, pausar ou iniciar outro rascunho. Uma redefinição no cliente não cancela uma gravação já aceita pelo servidor. Serialize os salvamentos, verifique versões e aguarde a confirmação antes de anunciar uma exclusão no servidor. Este exemplo não inclui salvamento automático nem exclusão de dados armazenados.

Teste antes de integrar

Cancele as duas confirmações e confira se título e documento continuam intactos. Limpe apenas o documento. Edite os dois campos e restaure o formulário inicial. Teste teclado, títulos longos e telas de 320px. Não prometa que Desfazer recuperará uma substituição programática; mantenha um rascunho separado se precisar de recuperação.

Leia a seguir