How to paste as plain text in a contenteditable editor
Published 2026-10-26 · Works in all current browsers, with or without a framework.
Why pasted content brings its formatting along
When a user copies from Word, Google Docs or a web page, the clipboard stores several versions of the same content, usually text/plain and text/html. A contenteditable element inserts the HTML version by default. That HTML carries inline styles, <span> and <font> wrappers, class names, Office-specific tags and sometimes tracking images or event handler attributes.
The result is text in the wrong font and size, markup your stylesheet cannot override, and stored HTML that is unsafe to render for other users. The fix is to take over the paste.
Option 1: always paste plain text
Cancel the default paste and insert only the text/plain version. insertText replaces the current selection, places the caret after the inserted text and adds the change to the browser's undo stack.
const editor = document.querySelector('#editor');
editor.addEventListener('paste', (event) => {
// Stop the browser from inserting the clipboard's HTML version
event.preventDefault();
const text = event.clipboardData.getData('text/plain');
if (!text) return;
// insertText replaces the selection and keeps native undo (Ctrl+Z) working
document.execCommand('insertText', false, text);
});execCommand is marked deprecated but every current browser still supports it, and it is the only API that inserts text and keeps native undo. If you cannot use it, insert through the Range API. That keeps line breaks as <br> but does not create an undo step, so pair it with your own history.
function insertPlainText(text) {
const sel = document.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
range.deleteContents();
// Turn line breaks into <br> so multi-line text keeps its shape
const fragment = document.createDocumentFragment();
text.split(/\r\n|\r|\n/).forEach((line, i) => {
if (i > 0) fragment.appendChild(document.createElement('br'));
fragment.appendChild(document.createTextNode(line));
});
const last = fragment.lastChild;
range.insertNode(fragment);
// Put the caret after the inserted text
range.setStartAfter(last);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}Option 2: contenteditable="plaintext-only"
For fields that should never contain formatting, such as a title or a chat message, the browser can do the work: plaintext-only converts pasted HTML to text and ignores formatting shortcuts. It needs no JavaScript, but it also rules out bold, links and lists, so it is not an option for a rich text editor.
<!-- The browser itself only accepts plain text: no bold, no pasted HTML -->
<div contenteditable="plaintext-only">Type or paste here</div>Option 3: keep basic formatting, remove the rest
Most rich text editors want something in between: keep paragraphs, bold, italic, links and lists, and throw away fonts, colors, classes and anything executable. Parse the text/html version with DOMParser, which produces an inert document, then rebuild it node by node from an allowlist. Elements are recreated rather than copied, so no attribute you did not explicitly allow can survive.
const ALLOWED_TAGS = new Set(['P', 'BR', 'STRONG', 'B', 'EM', 'I', 'U', 'A', 'UL', 'OL', 'LI', 'H2', 'H3', 'BLOCKQUOTE']);
const ALLOWED_SCHEMES = ['http:', 'https:', 'mailto:'];
function cleanNode(node, out) {
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
out.appendChild(document.createTextNode(child.textContent));
} else if (child.nodeType === Node.ELEMENT_NODE) {
if (ALLOWED_TAGS.has(child.tagName)) {
// Rebuild the element: no class, style, id or on* attributes survive
const el = document.createElement(child.tagName);
if (child.tagName === 'A') {
const href = child.getAttribute('href') || '';
try {
if (ALLOWED_SCHEMES.includes(new URL(href, location.href).protocol)) el.setAttribute('href', href);
} catch { /* invalid URL: drop the href */ }
}
cleanNode(child, el);
out.appendChild(el);
} else if (!['SCRIPT', 'STYLE', 'IFRAME', 'OBJECT', 'TEMPLATE'].includes(child.tagName)) {
// Unwrap unknown tags (span, font, o:p, div...) but keep their text
cleanNode(child, out);
}
}
}
return out;
}
editor.addEventListener('paste', (event) => {
const html = event.clipboardData.getData('text/html');
if (!html) return; // plain text only: let the default paste run
event.preventDefault();
// DOMParser builds an inert document: scripts do not run, images do not load
const doc = new DOMParser().parseFromString(html, 'text/html');
const clean = cleanNode(doc.body, document.createElement('div'));
document.execCommand('insertHTML', false, clean.innerHTML);
});Keep the allowlist in sync with what your editor's toolbar can create. If users cannot make a heading, pasting one should not create it either. Run the same sanitizer on the server before you store or render the HTML: a paste handler protects the editor, not your database.
React and Vue
The clipboard API is the same inside a framework. Attach the handler with the framework's paste event and keep the logic identical.
function PlainTextEditable() {
const onPaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
e.preventDefault();
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
};
return <div contentEditable suppressContentEditableWarning onPaste={onPaste} />;
}<template>
<div contenteditable @paste.prevent="onPaste" />
</template>
<script setup>
const onPaste = (e) => {
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
};
</script>Full editor setups are covered in the React and Vue rich text editor guides.
Checklist
- The paste handler calls preventDefault() before inserting anything
- Plain text is inserted with insertText so Ctrl+Z still undoes the paste
- Pasted HTML is rebuilt from an allowlist of tags, never inserted as-is
- Links keep only http, https or mailto URLs
- The allowlist matches what the toolbar can create
- The server sanitizes again before storing or rendering
- Tested with content copied from Word, Google Docs and a web page
How Scribe Editor handles paste
Scribe takes over every paste. When the clipboard has HTML, it runs it through the editor's sanitizer, which keeps semantic markup such as bold, italic, links, lists and headings and removes scripts, iframes, event handlers, Word styles and tracking pixels. When there is only plain text, it inserts the text. The allowlist is configurable, so the paste rules match your toolbar. See paste sanitization in the features docs and the security section for details.
import { Scribe } from 'scribejs-editor';
// Pasted HTML is sanitized against an allowlist before it is inserted;
// clipboard data with no HTML is inserted as plain text.
const editor = Scribe.init('#editor', {
sanitize: {
allowedTags: ['p', 'strong', 'em', 'a', 'ul', 'ol', 'li'],
allowedSchemes: ['https'],
},
});Clean paste out of the box
Scribe Editor is an MIT-licensed rich text editor under 50KB with built-in paste sanitization, toolbars that keep the selection, and a direct API for React, Vue, Svelte and Vanilla JS.
Paste as plain text: FAQ
How do I force paste as plain text in a contenteditable div?
Add a paste listener that calls event.preventDefault(), reads event.clipboardData.getData('text/plain'), and inserts that string with document.execCommand('insertText', false, text). The browser never inserts the clipboard's HTML, so all fonts, colors and classes are dropped.
Why does pasting from Word or Google Docs add so much markup?
The clipboard holds several versions of the copied content. When the text/html version exists, the browser inserts it, including inline styles, span and font tags, class names and Office-specific elements. Reading text/plain or sanitizing text/html in a paste handler is the only reliable way to control what lands in the editor.
Does preventing the default paste break undo?
Not if you insert with document.execCommand('insertText') or ('insertHTML'): the browser records those as normal edits, so Ctrl+Z undoes the paste. Inserting with the Range API (insertNode) bypasses the native undo stack, so use it only as a fallback or when your editor keeps its own history.
What does contenteditable="plaintext-only" do?
It makes the element accept only plain text: pasted HTML is converted to text and formatting shortcuts such as Ctrl+B do nothing. It suits inputs like titles or chat messages without formatting, but not a rich text editor where users should still be able to apply bold, links or lists.
Is it safe to insert pasted HTML after parsing it with DOMParser?
Parsing with DOMParser is safe because the resulting document is inert, but inserting its HTML as-is is not: event handler attributes and javascript: links would survive. Rebuild the content from an allowlist of tags and URL schemes, as in the example above, or use a maintained sanitizer.