dompurify vs sanitize-html vs xss vs xss-filters
Web 应用中的 HTML 安全过滤方案对比
dompurifysanitize-htmlxssxss-filters

Web 应用中的 HTML 安全过滤方案对比

这四个库都用于防止跨站脚本攻击(XSS),但适用场景不同。dompurify 专注于浏览器端 DOM 清洗,sanitize-html 和 xss 主要用于 Node.js 服务端字符串处理,而 xss-filters 是较早期的方案。它们通过白名单机制移除危险标签和属性,确保用户输入的内容在渲染时不会执行恶意代码。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
dompurify017,3171.8 MB010 小时前(MPL-2.0 OR Apache-2.0)
sanitize-html04,59975.7 kB1356 天前MIT
xss05,314145 kB692 年前MIT
xss-filters01,071-710 年前-

Web 应用中的 HTML 安全过滤方案对比

在前端开发中,处理用户提交的富文本内容是一个常见且高风险的任务。如果不加处理直接渲染,攻击者可能注入恶意脚本(XSS)。dompurify、sanitize-html、xss 和 xss-filters 都是为了解决这个问题而生的工具,但它们的設計思路、运行环境和维护状态有很大区别。本文将从架构师的角度,深入对比这四个方案。

🖥️ 运行环境:浏览器端 vs 服务端

选择库的第一步是确认代码运行在哪里。浏览器端操作的是 DOM 树,而服务端操作的是 HTML 字符串。

dompurify 最初为浏览器设计,利用浏览器的 DOM API 进行解析和清洗,安全性极高。后来通过依赖 jsdom 也支持了 Node.js 环境。

// dompurify: 浏览器环境
const clean = DOMPurify.sanitize(dirty);

// dompurify: Node.js 环境 (需引入 jsdom)
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
const clean = DOMPurify.sanitize(dirty);

sanitize-html 是纯 Node.js 库,基于 htmlparser2 解析字符串。它不依赖浏览器环境,适合服务端渲染(SSR)或后台处理。

// sanitize-html: Node.js 环境
const sanitizeHtml = require('sanitize-html');
const clean = sanitizeHtml(dirty, { allowedTags: ['b', 'i', 'em', 'strong', 'a'] });

xss 也是专为 Node.js 设计的轻量级库,通过正则和状态机解析字符串,速度快,适合高并发场景。

// xss: Node.js 环境
const filterXSS = require('xss');
const clean = filterXSS(dirty);

xss-filters 是 Yahoo 早期开源的库,主要针对 Node.js 环境,但架构较老,不再推荐用于新环境。

// xss-filters: Node.js 环境
const xssFilters = require('xss-filters');
const clean = xssFilters.inHTMLData(dirty);

⚙️ 配置灵活性:白名单控制

安全的本质是信任白名单。这四个库都允许自定义允许通过的标签和属性,但配置方式不同。

dompurify 使用 ALLOWED_TAGS 和 ALLOWED_ATTR 配置项,语义清晰。

// dompurify: 自定义白名单
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_TAGS: ['a', 'p'],
  ALLOWED_ATTR: ['href', 'class']
});

sanitize-html 提供非常细致的配置,甚至可以为每个标签单独定义允许的属性。

// sanitize-html: 精细控制
const clean = sanitizeHtml(dirty, {
  allowedTags: ['a', 'p'],
  allowedAttributes: {
    'a': ['href', 'class'],
    'p': ['class']
  }
});

xss 使用 whiteList 对象,结构紧凑,适合快速配置。

// xss: 自定义白名单
const clean = filterXSS(dirty, {
  whiteList: {
    a: ['href', 'class'],
    p: ['class']
  }
});

xss-filters 配置能力较弱,主要提供几个固定的过滤函数,自定义白名单较为麻烦。

// xss-filters: 固定过滤模式
// 不支持像其他库那样灵活的白名单配置对象
const clean = xssFilters.inHTMLData(dirty);

🛡️ 安全模型与维护状态

安全库的生命力在于持续更新。随着新攻击手法的出现,库必须及时修补漏洞。

dompurify 由安全专家维护,响应速度极快,是业界公认的安全基准。如果你处理敏感数据,这是首选。

sanitize-html 维护稳定,社区活跃,适合企业级后端服务。它的解析器 htmlparser2 也很成熟。

xss 由国内开发者维护,对中文语境下的 XSS 攻击有较好支持,更新频率尚可,适合国内项目。

xss-filters 更新缓慢,社区讨论较少。虽然它在过去很流行,但现在已属于遗留技术。新项目中引入它会增加维护负担和安全风险。

📊 功能对比总结

特性dompurifysanitize-htmlxssxss-filters
主要环境浏览器 / Node.jsNode.jsNode.jsNode.js
解析方式DOM API / jsdom字符串解析字符串解析字符串解析
配置难度中等高(灵活)低低(固定)
维护状态非常活跃活跃活跃停滞
推荐场景前端富文本编辑器服务端邮件/内容服务端轻量过滤旧项目维护

💡 架构师建议

在选择 HTML 过滤方案时,不要只看功能列表,要看它是否匹配你的系统架构。

  1. 前端优先:如果过滤逻辑主要在浏览器执行(例如富文本编辑器预览),dompurify 是唯一推荐的选择。它利用浏览器原生能力,比正则更安全。
  2. 服务端优先:如果是在 Node.js 后端存储或发送邮件,sanitize-html 提供最强的控制力,而 xss 提供最好的性能。
  3. 避免遗留:除非你正在维护一个五年前启动的老项目,否则不要在新代码中引入 xss-filters。它的功能已被更好的方案取代。
  4. 双重防护:在高度敏感的系统中,建议同时在服务端和客户端进行过滤。客户端为了用户体验,服务端为了数据安全。

🔚 结论

这四个库都能解决 XSS 问题,但 dompurify 和 sanitize-html 代表了现代最佳实践。xss 是一个优秀的轻量级替代品,特别适合国内 Node.js 生态。而 xss-filters 已逐渐退出历史舞台。根据你的运行环境做出选择 — 浏览器选 dompurify,服务端选 sanitize-html 或 xss。

如何选择: dompurify vs sanitize-html vs xss vs xss-filters

  • dompurify:

    如果你的应用主要在浏览器端运行,或者需要处理复杂的 DOM 结构,选择 dompurify。它是目前安全性最高、维护最活跃的方案,支持浏览器和 Node.js 环境。

  • sanitize-html:

    如果你在 Node.js 服务端处理 HTML 字符串(例如邮件发送、CMS 内容存储),选择 sanitize-html。它的配置项非常详细,适合需要精细控制标签和属性的场景。

  • xss:

    如果你需要轻量级的 Node.js 解决方案,且关注性能和中文字符集支持,选择 xss。它在国内生态中广泛使用,配置简单且效率高。

  • xss-filters:

    仅建议在维护旧项目时使用,新项目不建议选用。该库更新频率较低,相比其他方案缺乏最新的安全补丁和功能改进,存在潜在风险。

dompurify的README

DOMPurify

npm License Downloads dependents npm package minimized gzipped size (select exports) Cloudback

OpenSSF Best Practices Build & Test OpenSSF Scorecard Socket Badge snyk.io package health

DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG.

It's also very simple to use and get started with. DOMPurify was started in February 2014 and, meanwhile, has reached version v3.4.14.

DOMPurify runs as JavaScript and works in all modern browsers (Safari (10+), Opera (15+), Edge, Firefox and Chrome - as well as almost anything else using Blink, Gecko or WebKit). It doesn't break on MSIE or other legacy browsers. It simply does nothing.

Note that DOMPurify v2.5.9 is the latest version supporting MSIE. For important security updates compatible with MSIE, please use the 2.x branch.

Our automated tests cover 9 browser/OS combinations on the current engines (Chromium, Firefox, and WebKit across Ubuntu, macOS, and Windows) on every push, and a separate matrix re-runs the suite on older engine snapshots (back to roughly Chromium 110, Firefox 108 and WebKit 16.4, around three years old) so regressions on outdated browsers get caught too. We also run Node.js v20, v22, v24, v25 and v26 with DOMPurify on jsdom. Older Node versions are known to work as well, but hey... no guarantees.

DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our Security Goals & Threat Model. Please, read it. Like, really. And if you enjoy the gory details, the Attack Classes & Bypass History page catalogs the parser-mutation, namespace, clobbering, and template tricks DOMPurify defends against.

The DOMPurify project inspired the creation of the HTML Sanitizer API, which is already shipping in many browsers. The same capability is now being standardized directly in the WHATWG HTML specification.

Table of Contents

What does it do?

DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with e.g. a string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It's also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.

How do I use it?

It's easy. Just include DOMPurify on your website.

Using the unminified version (source-map available)

<script type="text/javascript" src="dist/purify.js"></script>

Using the minified and tested production version (source-map available)

<script type="text/javascript" src="dist/purify.min.js"></script>

Afterwards you can sanitize strings by executing the following code:

const clean = DOMPurify.sanitize(dirty);

Or maybe this, if you love working with Angular or alike:

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize('<b>hello there</b>');

The resulting HTML can be written into a DOM element using innerHTML or the DOM using document.write(). That is fully up to you. Note that by default, we permit HTML, SVG and MathML. If you only need HTML, which might be a very common use-case, you can easily set that up as well:

const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });

Is there any foot-gun potential?

Well, please note, if you first sanitize HTML and then modify it afterwards, you might easily void the effects of sanitization. If you feed the sanitized markup to another library after sanitization, please be certain that the library doesn't mess around with the HTML on its own. See the Security Goals & Threat Model for safe-usage recipes and the tags/attributes worth thinking twice about, and Attack Classes & Bypass History for why post-processing and changing the markup context defeat sanitization.

Okay, makes sense, let's move on

After sanitizing your markup, you can also have a look at the property DOMPurify.removed and find out, what elements and attributes were thrown out. Please do not use this property for making any security critical decisions. This is just a little helper for curious minds.

Running DOMPurify on the server

DOMPurify technically also works server-side with Node.js. Our support strives to follow the Node.js release cycle.

Running DOMPurify on the server requires a DOM to be present, which is probably no surprise. Usually, jsdom is the tool of choice and we strongly recommend to use the latest version of jsdom.

Why? Because older versions of jsdom are known to be buggy in ways that result in XSS even if DOMPurify does everything 100% correctly. There are known attack vectors in, e.g. jsdom v19.0.0 that are fixed in jsdom v20.0.0 - and we really recommend to keep jsdom up to date because of that.

Please also be aware that tools like happy-dom exist but are not considered safe at this point. Combining DOMPurify with happy-dom is currently not recommended and will likely lead to XSS. For background on why the server-side DOM you choose is part of your trusted computing base, see Attack Classes & Bypass History.

Other than that, you are fine to use DOMPurify on the server. Probably. This really depends on jsdom or whatever DOM you utilize server-side. If you can live with that, this is how you get it to work:

npm install dompurify
npm install jsdom

For jsdom (please use an up-to-date version), this should do the trick:

const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');

const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
const clean = DOMPurify.sanitize('<b>hello there</b>');

Or even this, if you prefer working with imports:

import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';

const window = new JSDOM('').window;
const purify = DOMPurify(window);
const clean = purify.sanitize('<b>hello there</b>');

If you have problems making it work in your specific setup, consider looking at the amazing isomorphic-dompurify project which solves lots of problems people might run into.

npm install isomorphic-dompurify
import DOMPurify from 'isomorphic-dompurify';

const clean = DOMPurify.sanitize('<s>hello</s>');

Is there a demo?

Of course there is a demo! Play with DOMPurify

What if I find a security bug?

First of all, please immediately contact us via email so we can work on a fix. PGP key

Also, you probably qualify for a bug bounty! The fine folks over at Fastmail use DOMPurify for their services and added our library to their bug bounty scope. So, if you find a way to bypass or weaken DOMPurify, please also have a look at their website and the bug bounty info.

Some purification samples please?

How does purified markup look like? Well, the demo shows it for a big bunch of nasty elements. But let's also show some smaller examples!

DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="https://raw.githubusercontent.com/cure53/DOMPurify/HEAD/x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abc<iframe//src=jAva&Tab;script:alert(3)>def</p>'); // becomes <p>abc</p>
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><li><a href="https://github.com/cure53/DOMPurify/blob/HEAD///google.com">click</a></li></ul>

These are just a taste. For the full taxonomy of attack classes these samples come from - mutation XSS, namespace confusion, DOM clobbering, rawtext breakouts, and more - see Attack Classes & Bypass History.

What is supported?

DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery $() and elm.html() API without any known problems. For the exact set of elements and attributes permitted by default, see the Default TAGs & ATTRIBUTEs allow-list & blocklist wiki page.

What about legacy browsers like Internet Explorer?

DOMPurify does nothing at all. It simply returns exactly the string that you fed it. DOMPurify exposes a property called isSupported, which tells you whether it will be able to do its job, so you can come up with your own backup plan.

What about DOMPurify and Trusted Types?

In version 1.0.9, support for the Trusted Types API (MDN) was added to DOMPurify. In version 2.0.0, a config flag was added to control DOMPurify's behavior regarding this.

When DOMPurify.sanitize is used in an environment where the Trusted Types API is available and RETURN_TRUSTED_TYPE is set to true, it tries to return a TrustedHTML value instead of a string (the behavior for RETURN_DOM and RETURN_DOM_FRAGMENT config options does not change).

Note that in order to create a policy in trustedTypes using DOMPurify, RETURN_TRUSTED_TYPE: false is required, as createHTML expects a normal string, not TrustedHTML. The example below shows this.

window.trustedTypes.createPolicy('default', {
  createHTML: (to_escape) =>
    DOMPurify.sanitize(to_escape, { RETURN_TRUSTED_TYPE: false }),
});

When no TRUSTED_TYPES_POLICY is supplied, DOMPurify attempts to create its own internal Trusted Types policy named dompurify. If your page already defines its own policy together with a strict CSP (for example trusted-types my-organization) that does not allow a policy named dompurify, this attempt is blocked by the browser and logs a TrustedTypes policy dompurify could not be created. warning along with a CSP violation.

To stop DOMPurify from creating its internal fallback policy, pass TRUSTED_TYPES_POLICY: null. This is the right choice when you call DOMPurify.sanitize from inside your own policy's createHTML, and it means you do not have to add dompurify to your CSP's trusted-types allowlist.

window.trustedTypes.createPolicy('my-organization', {
  createHTML: (input) =>
    DOMPurify.sanitize(input, { TRUSTED_TYPES_POLICY: null }),
});

Do not pass your own wrapping policy back to DOMPurify as its TRUSTED_TYPES_POLICY (for example via DOMPurify.setConfig({ TRUSTED_TYPES_POLICY: myPolicy })) when that policy's createHTML already calls DOMPurify.sanitize. That is circular by definition - sanitizing would call the policy, which sanitizes by calling DOMPurify again - and DOMPurify will throw a descriptive TypeError to prevent the infinite recursion. Your own policy should call DOMPurify; DOMPurify should not be configured to call your policy.

If you want this default-policy pattern applied across an entire page automatically - so that every HTML sink is sanitized, including legacy code, third-party widgets, and the thousands of innerHTML assignments you cannot easily find or rewrite - have a look at DOMFortify. It installs exactly such a Trusted Types default policy backed by DOMPurify and refuses script sinks (eval, script.src, ...) outright. It is a deliberately separate project: DOMPurify stays a focused sanitizer, and DOMFortify handles the document-wide enforcement layer that is intentionally out of DOMPurify's scope.

Can I configure DOMPurify?

Yes. The included default configuration values are pretty good already - but you can of course override them. Check out the /demos folder to see a bunch of examples on how you can customize DOMPurify.

Before you widen the allow-list (ADD_TAGS, ADD_ATTR, CUSTOM_ELEMENT_HANDLING, …) or relax a default, it's worth skimming the tags and attributes to think twice about - a few are dangerous in non-obvious ways.

General settings

// strip {{ ... }}, ${ ... } and <% ... %> to make output safe for template systems
// be careful please, this mode is not recommended for production usage.
// allowing template parsing in user-controlled HTML is not advised at all.
// only use this mode if there is really no alternative.
const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_TEMPLATES: true });

// change how e.g. comments containing risky HTML characters are treated.
// be very careful, this setting should only be set to `false` if you really only handle
// HTML and nothing else, no SVG, MathML or the like.
// Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_XML: false });

Control our allow-lists and block-lists

// allow only <b> elements, very strict
const clean = DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] });

// allow only <b> and <q> with style attributes
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_TAGS: ['b', 'q'],
  ALLOWED_ATTR: ['style'],
});

// allow all safe HTML elements but neither SVG nor MathML
// note that the USE_PROFILES setting will override the ALLOWED_TAGS setting
// so don't use them together
const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });

// allow all safe SVG elements and SVG Filters, no HTML or MathML
const clean = DOMPurify.sanitize(dirty, {
  USE_PROFILES: { svg: true, svgFilters: true },
});

// allow all safe MathML elements and SVG, but no SVG Filters
const clean = DOMPurify.sanitize(dirty, {
  USE_PROFILES: { mathMl: true, svg: true },
});

// change the default namespace from HTML to something different
const clean = DOMPurify.sanitize(dirty, {
  NAMESPACE: 'http://www.w3.org/2000/svg',
});

// leave all safe HTML as it is and add <style> elements to block-list
const clean = DOMPurify.sanitize(dirty, { FORBID_TAGS: ['style'] });

// leave all safe HTML as it is and add style attributes to block-list
const clean = DOMPurify.sanitize(dirty, { FORBID_ATTR: ['style'] });

// extend the existing array of allowed tags and add <my-tag> to allow-list
const clean = DOMPurify.sanitize(dirty, { ADD_TAGS: ['my-tag'] });

// extend the existing array of allowed attributes and add my-attr to allow-list
const clean = DOMPurify.sanitize(dirty, { ADD_ATTR: ['my-attr'] });

// use functions to control which additional tags and attributes are allowed
const allowlist = {
  one: ['attribute-one'],
  two: ['attribute-two'],
};
const clean = DOMPurify.sanitize(
  '<one attribute-one="1" attribute-two="2"></one><two attribute-one="1" attribute-two="2"></two>',
  {
    ADD_TAGS: (tagName) => {
      return Object.keys(allowlist).includes(tagName);
    },
    ADD_ATTR: (attributeName, tagName) => {
      return allowlist[tagName]?.includes(attributeName) || false;
    },
  }
); // <one attribute-one="1"></one><two attribute-two="2"></two>

// prohibit ARIA attributes, leave other safe HTML as is (default is true)
const clean = DOMPurify.sanitize(dirty, { ALLOW_ARIA_ATTR: false });

// prohibit HTML5 data attributes, leave other safe HTML as is (default is true)
const clean = DOMPurify.sanitize(dirty, { ALLOW_DATA_ATTR: false });

Control behavior relating to Custom Elements

// DOMPurify allows to define rules for Custom Elements. When using the CUSTOM_ELEMENT_HANDLING
// literal, it is possible to define exactly what elements you wish to allow (by default, none are allowed).
//
// The same goes for their attributes. By default, the built-in or configured allow.list is used.
//
// You can use a RegExp literal to specify what is allowed or a predicate, examples for both can be seen below.
// When using a predicate function for attributeNameCheck, it can optionally receive the tagName as a second parameter
// for more granular control over which attributes are allowed for specific elements.
// The default values are very restrictive to prevent accidental XSS bypasses. Handle with great care!

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: null, // no custom elements are allowed
      attributeNameCheck: null, // default / standard attribute allow-list is used
      allowCustomizedBuiltInElements: false, // no customized built-ins allowed
    },
  }
); // <div is=""></div>

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: /^foo-/, // allow all tags starting with "foo-"
      attributeNameCheck: /baz/, // allow all attributes containing "baz"
      allowCustomizedBuiltInElements: true, // customized built-ins are allowed
    },
  }
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>

const clean = DOMPurify.sanitize(
  '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: (tagName) => tagName.match(/^foo-/), // allow all tags starting with "foo-"
      attributeNameCheck: (attr) => attr.match(/baz/), // allow all containing "baz"
      allowCustomizedBuiltInElements: true, // allow customized built-ins
    },
  }
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>

// Example with attributeNameCheck receiving tagName as a second parameter
const clean = DOMPurify.sanitize(
  '<element-one attribute-one="1" attribute-two="2"></element-one><element-two attribute-one="1" attribute-two="2"></element-two>',
  {
    CUSTOM_ELEMENT_HANDLING: {
      tagNameCheck: (tagName) => tagName.match(/^element-(one|two)$/),
      attributeNameCheck: (attr, tagName) => {
        if (tagName === 'element-one') {
          return ['attribute-one'].includes(attr);
        } else if (tagName === 'element-two') {
          return ['attribute-two'].includes(attr);
        } else {
          return false;
        }
      },
      allowCustomizedBuiltInElements: false,
    },
  }
); // <element-one attribute-one="1"></element-one><element-two attribute-two="2"></element-two>

Control behavior relating to URI values

// extend the existing array of elements that can use Data URIs
const clean = DOMPurify.sanitize(dirty, { ADD_DATA_URI_TAGS: ['a', 'area'] });

// extend the existing array of elements that are safe for URI-like values (be careful, XSS risk)
const clean = DOMPurify.sanitize(dirty, { ADD_URI_SAFE_ATTR: ['my-attr'] });

Control permitted attribute values

// allow external protocol handlers in URL attributes (default is false, be careful, XSS risk)
// by default only http, https, ftp, ftps, tel, mailto, callto, sms, cid, xmpp and matrix are allowed.
const clean = DOMPurify.sanitize(dirty, { ALLOW_UNKNOWN_PROTOCOLS: true });

// allow specific protocol handlers in URL attributes via regex (default is false, be careful, XSS risk)
// by default only (protocol-)relative URLs, http, https, ftp, ftps, tel, mailto, callto, sms, cid, xmpp and matrix are allowed.
// Default RegExp: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_URI_REGEXP:
    /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
});

Influence the return-type

// return a DOM HTMLBodyElement instead of an HTML string (default is false)
const clean = DOMPurify.sanitize(dirty, { RETURN_DOM: true });

// return a DOM DocumentFragment instead of an HTML string (default is false)
const clean = DOMPurify.sanitize(dirty, { RETURN_DOM_FRAGMENT: true });

// use the RETURN_TRUSTED_TYPE flag to turn on Trusted Types support if available
const clean = DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true }); // will return a TrustedHTML object instead of a string if possible

// use a provided Trusted Types policy
const clean = DOMPurify.sanitize(dirty, {
  // supplied policy must define createHTML and createScriptURL
  TRUSTED_TYPES_POLICY: trustedTypes.createPolicy('dompurify', {
    createHTML(s) {
      return s;
    },
    createScriptURL(s) {
      return s;
    },
  }),
});

// opt out of DOMPurify's internal `dompurify` Trusted Types policy entirely
// (useful when your CSP `trusted-types` allowlist does not include `dompurify`)
const clean = DOMPurify.sanitize(dirty, { TRUSTED_TYPES_POLICY: null });

Influence how we sanitize

// 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'],
});

// extend the default FORBID_CONTENTS list to also remove <a> elements under <p> elements
const clean = DOMPurify.sanitize(dirty, {
  ADD_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',
});

Influence where we sanitize

// use the IN_PLACE mode to sanitize a node "in place", which is much faster depending on how you use DOMPurify
const dirty = document.createElement('a');
dirty.setAttribute('href', 'javascript:alert(1)');

const clean = DOMPurify.sanitize(dirty, { IN_PLACE: true }); // see https://github.com/cure53/DOMPurify/issues/288 for more info

There is even more examples here, showing how you can run, customize and configure DOMPurify to fit your needs.

Persistent Configuration

Instead of repeatedly passing the same configuration to DOMPurify.sanitize, you can use the DOMPurify.setConfig method. Your configuration will persist until your next call to DOMPurify.setConfig, or until you invoke DOMPurify.clearConfig to reset it. Remember that there is only one active configuration, which means once it is set, all extra configuration parameters passed to DOMPurify.sanitize are ignored.

Hooks

DOMPurify allows you to augment its functionality by attaching one or more functions with the DOMPurify.addHook method to one of the following hooks:

  • beforeSanitizeElements
  • uponSanitizeElement (No 's' - called for every element)
  • afterSanitizeElements
  • beforeSanitizeAttributes
  • uponSanitizeAttribute
  • afterSanitizeAttributes
  • beforeSanitizeShadowDOM
  • uponSanitizeShadowNode
  • afterSanitizeShadowDOM

It passes the currently processed DOM node, when needed a literal with verified node and attribute data and the DOMPurify configuration to the callback. Check out the MentalJS hook demo to see how the API can be used nicely.

Example:

DOMPurify.addHook(
  'uponSanitizeAttribute',
  function (currentNode, hookEvent, config) {
    // Do something with the current node
    // You can also mutate hookEvent for current node (i.e. set hookEvent.forceKeepAttr = true)
    // For other than 'uponSanitizeAttribute' hook types hookEvent equals to null
  }
);

A note on calling sanitize() from a hook

DOMPurify.sanitize() is not re-entrant. Please do not call it from inside a hook, or from a configuration callback such as CUSTOM_ELEMENT_HANDLING.tagNameCheck or attributeNameCheck. Those callbacks run in the middle of an active sanitizer pass.

A nested sanitize() call re-reads the configuration handed to it and, in doing so, replaces the configuration the outer pass is still using. The rest of the outer document is then sanitized against the nested call's configuration instead of yours. Since the nested call typically runs with the default configuration, a strict ALLOWED_TAGS allow-list can silently widen back to the default one part-way through a document, with no error and no warning.

If you need to sanitize nested markup, for example an HTML fragment carried inside an attribute value, you have two safe options. Either set your configuration once with DOMPurify.setConfig instead of passing it per call, since a persistent configuration is shared by the nested call and stays in effect for the whole pass; or collect the fragments during the hook and sanitize them with a separate sanitize() call after the outer one has returned.

Removed Configuration

OptionSinceNote
SAFE_FOR_JQUERY2.1.0No replacement required.

Continuous Integration

We are currently using GitHub Actions in combination with Playwright. This lets us confirm on every commit that everything works in the relevant modern browsers, and a separate scheduled and on-merge workflow re-runs the suite on older engine snapshots so breakage on outdated browsers is caught too. Check out the build logs here: https://github.com/cure53/DOMPurify/actions

You can further run local tests by executing npm run test.

All relevant commits will be signed with the key 0x24BB6BF4 for additional security (since 8th of April 2016).

Development and contributing

Installation (npm i)

We support npm officially. GitHub Actions workflow is configured to install dependencies using npm. When using a deprecated version of npm, we cannot fully ensure the versions of installed dependencies, which might lead to unanticipated problems.

Scripts

We use ESLint via xo as part of our pre-commit workflow to help ensure code consistency. In addition, we use Prettier for source and Markdown formatting, and /dist assets are built through rollup.

These are our npm scripts:

  • npm run dev to build the unminified UMD bundle while watching sources for changes
  • npm run test to lint the sources, run tests through jsdom, and run browser tests in Chromium via Playwright
    • npm run test:jsdom to only run tests through jsdom
    • npm run test:happydom to run the suite through happy-dom (an unsupported environment; kept as a robustness check, not a compatibility promise)
    • npm run test:browser to only run tests through Playwright
    • npm run test:browser:legacy to run the suite on older browser engines (point PW_MODULE at a pinned old Playwright install; see .github/workflows/legacy-browsers.yml)
    • npm run test:ci to run the CI test flow for jsdom and Playwright
    • npm run test:fuzz to run a small fuzzer covering sanitize() and CONFIG
  • npm run bench to run the jsdom micro-benchmark over the built dist/purify.cjs (build first; --json and --compare a.json b.json support A/B runs across branches - results are directional, confirm user-facing claims in real browsers)
  • npm run coverage to build an instrumented bundle, run the jsdom suite, and write a local HTML line/branch coverage report to coverage/index.html (jsdom scope only, not run in CI)
    • npm run build:cov to only build the instrumented coverage bundle
  • npm run lint to lint the sources using ESLint via xo
  • npm run format to format JavaScript/TypeScript and Markdown sources with Prettier
    • npm run format:js to only format JavaScript/TypeScript sources
    • npm run format:md to only format Markdown files
  • npm run build to build type declarations and distribution bundles, then fix and clean up generated types
    • npm run build:types to only emit TypeScript declaration files
    • npm run build:rollup to build all Rollup bundles
    • npm run build:umd to only build an unminified UMD bundle
    • npm run build:umd:min to only build a minified UMD bundle
    • npm run build:es to only build the ES module bundle
    • npm run build:cjs to only build the CommonJS bundle
    • npm run build:fix-types to post-process generated type files
    • npm run build:cleanup to clean up temporary generated type output
  • npm run verify-typescript to run the TypeScript verification script
  • npm run commit-amend-build to run the maintainer helper script for amending build output

Note: all run scripts triggered via npm run <script>.

There are more npm scripts but they are mainly to integrate with CI or are meant to be "private" for instance to amend build distribution files with every commit.

Security Mailing List

We maintain a mailing list that notifies whenever a security-critical release of DOMPurify was published. This means, if someone found a bypass and we fixed it with a release (which always happens when a bypass was found) a mail will go out to that list. This usually happens within minutes or a few hours after learning about a bypass. The list can be subscribed to here:

https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security

Feature releases will not be announced to this list.

Who contributed?

Many people have helped DOMPurify become what it is today, and they deserve to be acknowledged!

offset, Bankde, lukewarlow, DEMON1A, fg0x0, kodareef5, DavidOliver, 1Jesper1, bencalif, trace37labs, eddieran, christos-eth, researchatfluidattacks, frevadiscor, Rotzbua, binhpv, MariusRumpf, prasadrajandran, Cybozu 💛💸, hata6502 💸, openclaw 💸, intra-mart-dh 💸, nelstrom ❤️, hash_kitten ❤️, kevin_mizu ❤️, icesfont ❤️, reduckted ❤️, dcramer 💸, JGraph 💸, baekilda 💸, Healthchecks 💸, Sentry 💸, jarrodldavis 💸, CynegeticIO, ssi02014 ❤️, GrantGryczan, Lowdefy, granlem, oreoshake, tdeekens ❤️, peernohell ❤️, is2ei, SoheilKhodayari, franktopel, NateScarlet, neilj, fhemberger, Joris-van-der-Wel, ydaniv, terjanq, filedescriptor, ConradIrwin, gibson042, choumx, 0xSobky, styfle, koto, tlau88, strugee, oparoz, mathiasbynens, edg2s, dnkolegov, dhardtke, wirehead, thorn0, styu, mozfreddyb ❤️, mikesamuel, jorangreef, jimmyhchan, jameydeorio, jameskraus, hyderali, hansottowirtz, hackvertor, freddyb, flavorjones, djfarrelly, devd, camerondunford, buu700, buildog, alabiaga, Vector919, Robbert, GreLI, FuzzySockets, ArtemBernatskyy, @garethheyes, @shafigullin, @mmrupp, @irsdl,ShikariSenpai, ansjdnakjdnajkd, @asutherland, @mathias, @cgvwzq, @robbertatwork, @giutro, @CmdEngineer_, @avr4mit, davecardwell, Develop-KIM, asamuzaK, fishjojo1 ❤️, Rikuxx0, donmccurdy, hhk-png, elrion018, michalnieruchalski-tiugo, reey, KanhaKanhaiya, odaysec, Akokonunes, alirezarouhbakhsh, Jaybhade and especially @securitymb ❤️ & @masatokinugawa ❤️