← Blog 5 min read

HTML Sanitizer API: Safer Untrusted Markup

HTML Sanitizer API: Safer Untrusted Markup

Websites regularly display content they did not write themselves: profile descriptions, comments, support messages, imported documents, and text from content-management systems. Some of that content needs simple formatting such as headings, links, or lists. Treating it as raw HTML, however, can allow executable code or misleading page elements to enter a trusted interface.

The HTML Sanitizer API is designed to filter markup at the point where a page inserts it. It gives browsers a native, context-aware way to keep permitted structure while removing elements and attributes that can create cross-site scripting risks.

How the HTML Sanitizer API handles untrusted markup

HTML is not passive text. A script element can execute code, an event-handler attribute can react to a click, and certain embedded resources can trigger requests or confusing interface behavior. Copying an untrusted string into the document with an unsafe HTML insertion method can therefore change more than typography.

Safe Sanitizer API methods such as Element.setHTML(), ShadowRoot.setHTML(), and Document.parseHTML() parse a string and apply a sanitizer before the result reaches the page. The default safe configuration removes script-capable elements, event-handler attributes, and other markup associated with cross-site scripting or spoofing. MDN's HTML Sanitizer API overview provides the current method and support details.

This approach is useful because sanitization happens with knowledge of the HTML context. A browser parser understands which elements and attributes are meaningful at a particular insertion point. That is safer than trying to clean HTML with a few regular expressions, which cannot reliably model the language.

Safe and unsafe methods are deliberately separate

The platform also includes methods with names such as setHTMLUnsafe() and parseHTMLUnsafe(). The word “unsafe” is not decorative. Those methods can accept a sanitizer configuration, but they can also insert markup without the guarantees provided by the safe methods. A permissive configuration could allow dangerous content.

That distinction helps code reviewers see risk at the call site. If a project uses an unsafe method, the source of the markup, the sanitizer configuration, and the surrounding defenses deserve close inspection. A safe method is the better default when the content does not need features that the safety baseline removes.

The API's default sanitizer configuration is intentionally conservative. Developers may define a narrower custom policy, but a custom policy should begin with the minimum elements and attributes a feature actually needs. A comment box rarely needs forms, embedded frames, or active media controls.

Sanitization is one layer, not the whole security model

Sanitizing displayed markup does not validate a person's identity, confirm that a link is honest, or decide whether stored content belongs in a particular account. Authorization, input validation, output encoding, secure cookies, and server-side controls still have separate jobs.

Content Security Policy adds another valuable layer. It can restrict which scripts, styles, frames, and other resources the browser is allowed to load. Noorani's guide to Content Security Policy explains how those rules limit the damage of unexpected content. Sanitization tries to keep dangerous markup out; CSP helps constrain what can run if something slips through.

Trusted Types can further protect dangerous DOM insertion points by requiring approved objects instead of arbitrary strings. The safe Sanitizer API methods do not require Trusted Types, but the two systems can complement each other across a larger application. Teams can use safe insertion for ordinary rich content and enforce stricter review around the remaining unsafe sinks.

Links and visual deception still need attention

Markup can be technically non-executable yet still mislead someone. A link label may name one destination while pointing somewhere else. A block may imitate a sign-in prompt or place a button over trusted content. Sanitization reduces code execution risk, but product design must also limit the shapes untrusted content can take.

For community content, it is often sensible to allow paragraphs, emphasis, lists, and carefully processed links while rejecting forms and elaborate positioning. External links can be clearly indicated, and redirect parameters should be validated. The browser's protections against pop-ups and unexpected redirects are helpful, but the site should not create deceptive paths in the first place.

A practical sanitization workflow

A strong implementation starts by deciding whether HTML is necessary. Plain text is easier to secure and may be enough for many fields. If formatting is required, the application can define a small allowlist based on real product needs, sanitize at display time, and test hostile examples alongside normal content.

Server-side sanitization can protect emails, exports, search indexes, and older clients that never use the browser API. Client-side sanitization protects the final DOM insertion. Using both can be appropriate, provided the policies are maintained consistently and the original untrusted value is never inserted through a different path.

Developers should also account for browser support. The HTML Sanitizer API is not yet available everywhere. A well-maintained sanitization library can provide a fallback, while feature detection enables the native path where supported. Falling back must not mean falling back to raw innerHTML.

What users can notice

People cannot inspect every sanitization rule, but they can be cautious around rich content that asks for credentials, opens unfamiliar destinations, or imitates the site's own controls. Check the address bar before entering sensitive information, and treat embedded prompts inside comments or messages with skepticism.

For developers, the central principle is equally clear: untrusted markup should cross an explicit safety boundary before it becomes part of the document. The HTML Sanitizer API makes that boundary easier to express in the browser, while layered defenses keep the rest of the application honest.

Browse with more intention

Noorani brings prayer times, Qibla, tracker blocking, and privacy into one calm desktop browser built for how Muslims live online.

Download Noorani