sajad torkamani

What is DOMPurify?

DOMPurify is a JavaScript library that helps you sanitize strings on the client-side to strip out anything that can cause XSS attacks.

Quick usage

import DOMPurify from 'dompurify'

const sanitizedHtml = DOMPurify.sanitize('<img src=x onerror=prompt()>')

console.log(sanitizedHtml)
// => <img src="x">

You can use the demo tool here to see how DOMPurify will sanitize particular strings.

DOMPurify

Configure allowed tags and attributes for each usage

You can configure allowed tags and attributes for each usage like so:

// return entire document including <html> tags (default is false)
const clean = DOMPurify.sanitize(dirty, {WHOLE_DOCUMENT: true});

// disable DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here)
const clean = DOMPurify.sanitize(dirty, {SANITIZE_DOM: false});

// enforce strict DOM Clobbering protection via namespace isolation (default is false)
// when enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
// from JS variables by prefixing them with the string `user-content-`
const clean = DOMPurify.sanitize(dirty, {SANITIZE_NAMED_PROPS: true});

// keep an element's content when the element is removed (default is true)
const clean = DOMPurify.sanitize(dirty, {KEEP_CONTENT: false});

// glue elements like style, script or others to document.body and prevent unintuitive browser behavior in several edge-cases (default is false)
const clean = DOMPurify.sanitize(dirty, {FORCE_BODY: true});

// remove all <a> elements under <p> elements that are removed
const clean = DOMPurify.sanitize(dirty, {FORBID_CONTENTS: ['a'], FORBID_TAGS: ['p']});

// change the parser type so sanitized data is treated as XML and not as HTML, which is the default
const clean = DOMPurify.sanitize(dirty, {PARSER_MEDIA_TYPE: 'application/xhtml+xml'});

Set global configuration

DOMPurify.setConfig({yourOptions})

Using DOMPurify.setConfig() will persist your configuration until your next call to DOMPurify.setConfig() or until you use DOMPurify.clearConfig().

Using DOMPurify.setConfig() will mean any config parameters passed to DOMPurify.sanitize are ignored.

Default config

The default allowed tags can be found here. For HTML tags, look for the list of tags in the exported html object.

The default allowed attributes can be found here. For HTML attributes, look for the list of attributes in the exported html object.

Links