Sanitizing pasted HTML
Pasted HTML is untrusted input: parse it into an inert document, keep what your document model has a rule for, drop everything else, and insert the result as one undoable change. A strong answer allowlists rather than blocklists.
What it is
When someone pastes into a contenteditable region, the browser's default action is to insert the clipboard contents at the cursor. A paste handler can read what is on the clipboard through getData() on the event's clipboardData, and if it calls preventDefault() it takes over: the browser inserts nothing, and the handler decides what goes in. That hand-off is where sanitizing pasted HTML happens. Whatever a web page, a word processor or a mail client put on the clipboard is a string of markup you didn't write, and it can carry script elements, event handler attributes, links whose URL is itself a script, inline styles and tracking images.
Two jobs hide under the word sanitize, and a clear answer keeps them apart. The security job removes markup that could execute script: a general-purpose sanitizer such as DOMPurify is built for that, and its own samples show an img carrying an onerror handler reduced to a bare img with its src, and an iframe whose source is a script-scheme URL dropped from a paragraph. The fidelity job maps what survives onto your document model: ProseMirror does this through parseDOM rules in the schema, which say which DOM constructs become which nodes and marks, and the editor builds its default clipboard parser from those rules. The rule set acts as an allowlist for what can become part of the document; our advice is to also decide explicitly what unmatched markup should turn into.
Both jobs need a tree, not a string, and the tree must not be live. DOMParser.parseFromString() with text/html returns a separate in-memory document: its script elements are marked non-executable, no events fire, and handler attributes don't run. The returned document can still download resources named in iframe and img elements, so an inert parse is not a private one. The inertness ends when nodes move into the visible DOM: scripts and handlers that were dormant in the detached document are able to run once inserted, so filtering has to happen before insertion, not after.
editor.addEventListener('paste', (event: ClipboardEvent) => {
const data = event.clipboardData;
if (!data) return;
event.preventDefault(); // we insert, the browser does not
const html = data.getData('text/html');
const text = data.getData('text/plain');
const slice = html ? sliceFromHTML(html) : sliceFromText(text);
// one transaction: the history plugin records one inverse
view.dispatch(view.state.tr.replaceSelection(slice));
});
function sliceFromHTML(html: string) {
// detached document: scripts are inert, handlers never fire here
const doc = new DOMParser().parseFromString(html, 'text/html');
// schema parser: keeps what has a parse rule, unwraps or drops the rest
return schemaParser.parseSlice(doc.body, { preserveWhitespace: true });
}
// a style rule maps inline CSS to a mark the schema owns
const emphasis = {
parseDOM: [{ tag: 'em' }, { tag: 'i' }, { style: 'font-style=italic' }],
};When to use it
In a rich text editor, let the schema do the filtering. A parse rule matches a tag, a CSS selector such as div.myclass, or an inline style, so the basic emphasis mark accepts em, i and font-style: italic. That is where pasted inline styles go: a style the schema has a rule for becomes a mark, and a style with no rule has nothing to become, so in this design it is left behind. Copy and paste moves a slice, a span of content whose ends may be open, which is how half a paragraph can land inside an existing list item instead of starting a new block. The default clipboard parser comes from the schema, and you can override it when a source needs extra cleanup before parsing.
When the destination is a render sink rather than a document model, the browser's HTML Sanitizer API is the shortest path. Element.setHTML() is a drop-in for innerHTML that removes XSS-unsafe elements and attributes, and also removes elements the HTML specification doesn't permit as children of the target. You can pass a Sanitizer to allow the same set or fewer: an allow configuration lists elements and attributes, can unwrap elements with replaceWithChildrenElements, and a configuration holds allow lists or remove lists but not both. The default constructor allows the XSS-safe set and is a good base to tighten. Our advice: it's newer than the libraries, so check the browsers you support before you lean on it.
When you need a sanitizer across browsers today, reach for a vetted library. DOMPurify permits HTML, SVG and MathML by default, allows CSS and data- attributes, and can be narrowed to HTML with USE_PROFILES: { html: true }; widening the allowlist with ADD_TAGS or ADD_ATTR deserves a look at which tags are dangerous in non-obvious ways. Two warnings matter in an interview: modifying the output after sanitizing, or handing it to another library that rewrites markup, can void the sanitization, and on a browser it doesn't support the library returns the input unchanged, exposing isSupported so you can fall back to plain text.
Enforce the door, not just the filter. With Trusted Types enforced through the require-trusted-types-for CSP directive, injection sinks accept TrustedHTML rather than strings, so every string must pass through a policy's transformation function, which is where the sanitizer lives. That lets you audit sanitization in a few places instead of at every sink. A sanitizer library can return TrustedHTML directly or be called from inside your own policy's createHTML; in the second case pass TRUSTED_TYPES_POLICY: null so the library doesn't try to create its own policy and trip the CSP.
Make the paste one undoable change. The history plugin in ProseMirror watches transactions and stores each one's inverse, so a paste applied as a single transaction comes out with a single undo, while a paste split into many transactions can take several undos unless the history groups them. The same shape fits a grid: a paste of thousands of cells is one command that remembers the previous value of every cell it overwrote, and the recalculation it triggers is a consequence of the command, not part of what undo replays. See Undo and redo for grouping and Dependency graphs and incremental recalculation for why you want one recalculation per paste, not one per cell.
When not to
A plain-text destination has nothing to sanitize structurally. For a textarea, a single-line input or a grid cell, read the plain-text flavor and insert it as text; OWASP's first guideline for DOM-based XSS is to treat untrusted data as displayable text, and its third is to build dynamic interfaces with createElement, setAttribute and appendChild rather than markup strings. For a grid, we'd parse the plain-text flavor into cells first and fall back to the HTML table flavor when plain text loses something you need.
Content you display but never edit, such as a comment or a help panel, doesn't need a schema parser. A sanitizer at the sink, setHTML() or a library, is enough, because there is no model to map onto and no undo to group. Bringing an editor's parse pipeline to a read-only view adds a dependency for little gain.
A hand-written filter is usually the weaker option. The documented attack classes include mutation XSS, namespace confusion, DOM clobbering and raw-text breakouts; the common thread, as we read it, is that markup can mean one thing as a string and another once the browser has parsed and re-serialized it, which is exactly what a regex can't see. Offer paste as plain text as the simplest safe fallback instead.
Compared
| Approach | What it does | Reach for it when | What it costs |
|---|---|---|---|
Paste as plain text | Reads the text flavor and inserts text nodes | The destination has no formatting, or the source is untrusted enough that you want none | Loses every heading, list and link |
Browser Sanitizer API ( | Drops XSS-unsafe elements and attributes; allow or remove configurations | The target is a render sink and your supported browsers have it | No model mapping; newer than the libraries |
Sanitizer library (DOMPurify) | Allowlist over HTML, SVG and MathML; returns a string or | You need a cross-browser sanitizer and the output goes straight to a sink | Output must not be edited afterward; unsupported browsers get the input back |
Schema parser (ProseMirror | Maps tags and inline styles to nodes and marks; your rules decide what unmatched markup becomes | You have a document model and need fidelity; pair it with a sanitizer for safety | Quirks you want to keep each need a rule; cleanup before parsing is on you |
Trusted Types policy | With the CSP directive enforced, sinks accept | You want one audited door for all HTML insertion | Decides nothing about content; the policy still needs a sanitizer |
In a picture
Step 1 of 4
Take over the paste
The paste event fires; the handler calls preventDefault() and reads the HTML flavor from the clipboard. The browser inserts nothing on its own.