v146 · Security · Custom Sanitizer Config

Custom Sanitizer Config

The Sanitizer constructor accepts a configuration object that limits allowed elements and attributes below the already-safe default. Choose a preset for a common use case — comment box, rich-text editor, or plain text only — then edit the test HTML to see what survives each policy.

Chrome 146 required for the Sanitizer API. In older browsers the demo shows what the policy would produce but uses a simplified JavaScript fallback — not a real sanitizer.

choose a policy

Comment box

Allow bold, italic, and safe links. Block everything else including images and headings.

Rich text editor

Allow headings, paragraphs, lists, tables, links, and basic formatting. Block scripts and media.

Strict — links only

Allow only <a href> with safe URLs. All other markup stripped to text.

Plain text only

No elements at all — only raw text nodes survive. Equivalent to textContent.

live demo

Test HTML input:

Rendered result:
Serialized HTML after sanitization:

code for each policy

// Comment box — bold, italic, safe links only
const commentSanitizer = new Sanitizer({
  elements: ['b', 'i', 'em', 'strong', 'a', 'br'],
  attributes: { 'href': ['a'] },
});
output.setHTML(commentHTML, { sanitizer: commentSanitizer });

// Rich text editor
const richSanitizer = new Sanitizer({
  elements: [
    'h1','h2','h3','p','br','ul','ol','li',
    'b','i','em','strong','s','code','pre',
    'a','table','thead','tbody','tr','th','td'
  ],
  attributes: {
    'href': ['a'],
    'colspan': ['td','th'],
    'rowspan': ['td','th'],
  },
});

// Strict — links only
const linkSanitizer = new Sanitizer({
  elements: ['a'],
  attributes: { 'href': ['a'] },
});

// Plain text: no elements
const textOnlySanitizer = new Sanitizer({ elements: [] });
output.setHTML(html, { sanitizer: textOnlySanitizer });
// Result: only text nodes — identical to textContent assignment

see also