Skip to content
KitploitKITPLOIT
HerramientasExploitsBlog
Log in
Enviar
HerramientasExploitsBlog
Enviar

¡Herramientas de Hacking, PenTest y Ciberseguridad para tu Arsenal de Seguridad!

Kitploit es un directorio de herramientas de hacking, ciberseguridad y pentesting. Descubre las últimas actualizaciones de proyectos para encontrar vulnerabilidades, analizar sistemas, automatizar pruebas y fortalecer tu seguridad.

FeedsContactoPrivacidad© 2026 Kitploit

Directorio de Herramientas

Categorías

Ver todas las categorías
Loading categories
DOMPurify — DOMPurify: un sanitizador XSS exclusivo para DOM, súper rápido y ultra tolerante, para HTML, MathML y SVG. DOMPurify funciona con una configuración segura por defecto, pero ofrece mucha configurabilidad y hooks. Demo: | Kitploit
Herramientas/GitHubGitHub/cure53/dompurify
Herramientas DefensivasAnálisis EstáticoAnálisis de CódigoSeguridad WebAprendizaje y EducaciónSeguridad de APIs
GitHubcure53/dompurify

DOMPurify

DOMPurify: un sanitizador XSS exclusivo para DOM, súper rápido y ultra tolerante, para HTML, MathML y SVG. DOMPurify funciona con una configuración segura por defecto, pero ofrece mucha configurabilidad y hooks. Demo:

Ver Repositorio
17.3k860169hace 3 díasRevisado por Kitploit

Más Populares

Ver todos →

Descubre las herramientas más usadas por nuestra comunidad.

Explora todas las herramientas

Explora nuestra colección de herramientas

Ver todas las herramientas →
Sitio web
Compartir
# DOMPurify

[![npm](https://img.shields.io/npm/v/dompurify.svg)](https://www.npmjs.com/package/dompurify) [![License](https://img.shields.io/badge/license-MPL--2.0%20OR%20Apache--2.0-blue.svg)](https://github.com/cure53/DOMPurify/blob/main/LICENSE) [![Downloads](https://img.shields.io/npm/dm/dompurify.svg)](https://www.npmjs.com/package/dompurify) [![dependents](https://badgen.net/github/dependents-repo/cure53/dompurify?color=green&label=dependents)](https://github.com/cure53/DOMPurify/network/dependents) ![npm package minimized gzipped size (select exports)](https://img.shields.io/bundlejs/size/dompurify?color=%233C1&label=gzip) [![Cloudback](https://app.cloudback.it/badge/cure53/DOMPurify)](https://cloudback.it)

[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/12162/badge)](https://www.bestpractices.dev/projects/12162) [![Build & Test](https://github.com/cure53/DOMPurify/actions/workflows/build-and-test.yml/badge.svg?branch=main)](https://github.com/cure53/DOMPurify/actions/workflows/build-and-test.yml) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/cure53/DOMPurify/badge)](https://scorecard.dev/viewer/?uri=github.com/cure53/DOMPurify) [![Socket Badge](https://badge.socket.dev/npm/package/dompurify/latest)](https://badge.socket.dev/npm/package/dompurify/latest) [![snyk.io package health](https://img.shields.io/badge/snyk.io%20package%20health-97/100-brightgreen)](https://security.snyk.io/package/npm/dompurify)

DOMPurify es un saneador XSS para HTML, MathML y SVG que trabaja únicamente sobre el DOM, es extremadamente rápido y sumamente tolerante.

También es muy sencillo de usar y de empezar a utilizar. DOMPurify [se inició en febrero de 2014](https://github.com/cure53/DOMPurify/commit/a630922616927373485e0e787ab19e73e3691b2b) y, mientras tanto, ha alcanzado la versión **v3.4.17**.

DOMPurify se ejecuta como JavaScript y funciona en todos los navegadores modernos (Safari (10+), Opera (15+), Edge, Firefox y Chrome, así como en prácticamente cualquier otro que use Blink, Gecko o WebKit). No se rompe en MSIE ni en otros navegadores heredados. Simplemente no hace nada.

**Ten en cuenta que [DOMPurify v2.5.9](https://github.com/cure53/DOMPurify/releases/tag/2.5.9) es la última versión compatible con MSIE. Para actualizaciones de seguridad importantes compatibles con MSIE, utiliza la [rama 2.x](https://github.com/cure53/DOMPurify/tree/2.x).**

Nuestras pruebas automatizadas cubren 9 combinaciones de navegador/SO en los motores actuales (Chromium, Firefox y WebKit en Ubuntu, macOS y Windows) en cada push, y una matriz separada vuelve a ejecutar la suite sobre instantáneas de motores más antiguos (hasta aproximadamente Chromium 110, Firefox 108 y WebKit 16.4, de hace unos tres años) para que también se detecten regresiones en navegadores desactualizados. También ejecutamos Node.js v20, v22, v24, v25 y v26 con DOMPurify sobre [jsdom](https://github.com/jsdom/jsdom). Se sabe que las versiones anteriores de Node también funcionan, pero bueno... sin garantías.

DOMPurify está escrito por personas de seguridad con una amplia experiencia en ataques web y XSS. No temas. Para más detalles, lee también sobre nuestros [Objetivos de seguridad y modelo de amenazas](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model). Léelo. En serio. Y si disfrutas de los detalles escabrosos, la página [Clases de ataque e historial de bypass](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History) cataloga los trucos de mutación del parser, espacios de nombres, clobbering y plantillas contra los que DOMPurify se defiende.

El proyecto DOMPurify inspiró la creación de la [HTML Sanitizer API](https://wicg.github.io/sanitizer-api/#sanitizer), que ya se distribuye en [muchos navegadores](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API#browser_compatibility). Esa misma capacidad ahora se está estandarizando directamente en la [especificación HTML del WHATWG](https://html.spec.whatwg.org/#html-sanitization).

## Tabla de contenidos

- [¿Qué hace?](#what-does-it-do)
- [¿Cómo lo uso?](#how-do-i-use-it)
- [¿Hay una demo?](#is-there-a-demo)
- [¿Qué pasa si encuentro un bug de _seguridad_?](#what-if-i-find-a-security-bug)
- [¿Algunos ejemplos de purificación, por favor?](#some-purification-samples-please)
- [¿Qué es compatible?](#what-is-supported)
- [¿Qué pasa con los navegadores heredados como Internet Explorer?](#what-about-legacy-browsers-like-internet-explorer)
- [¿Qué pasa con DOMPurify y Trusted Types?](#what-about-dompurify-and-trusted-types)
- [¿Puedo configurar DOMPurify?](#can-i-configure-dompurify)
- [Configuración persistente](#persistent-configuration)
- [Hooks](#hooks)
- [Configuración eliminada](#removed-configuration)
- [Integración continua](#continuous-integration)
- [Lista de correo de seguridad](#security-mailing-list)
- [¿Quién contribuyó?](#who-contributed)

## ¿Qué hace?

DOMPurify sanitiza HTML y previene ataques XSS. Puedes alimentar DOMPurify con, por ejemplo, una cadena llena de HTML sucio y devolverá una cadena (a menos que se configure de otro modo) con HTML limpio. DOMPurify eliminará todo lo que contenga HTML peligroso y, de este modo, prevendrá ataques XSS y otras fechorías. Además, es tremendamente rápido. Usamos las tecnologías que proporciona el navegador y las convertimos en un filtro XSS. Cuanto más rápido sea tu navegador, más rápido será DOMPurify.

## ¿Cómo lo uso?

Es fácil. Solo tienes que incluir DOMPurify en tu sitio web.

### Usando la versión sin minificar (source-map disponible)

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

### Uso de la versión de producción minificada y probada (source-map disponible)

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

Después, puedes sanear cadenas ejecutando el siguiente código:

```js
const clean = DOMPurify.sanitize(dirty);
```

O quizás esto, si te encanta trabajar con Angular o similar:

```js
import DOMPurify from 'dompurify';

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

El HTML resultante se puede escribir en un elemento del DOM usando `innerHTML` o en el DOM usando `document.write()`. Eso depende completamente de ti.
Ten en cuenta que, por defecto, permitimos HTML, SVG **y** MathML. Si solo necesitas HTML, lo cual podría ser un caso de uso muy común, también puedes configurarlo fácilmente:

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

### ¿Existe algún potencial de foot-gun?

Bien, tenga en cuenta que si _primero_ sanitiza HTML y luego lo modifica _después_, podría fácilmente **anular los efectos de la sanitización**. Si alimenta el marcado sanitizado a otra biblioteca _después_ de la sanitización, asegúrese de que la biblioteca no manipule el HTML por su cuenta. Consulte [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model) para recetas de uso seguro y las etiquetas/atributos que merecen pensarse dos veces, y [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History) para entender por qué el posprocesamiento y el cambio del contexto del marcado anulan la sanitización.

### ¿Y si se pasa un nodo DOM en lugar de una cadena?

`DOMPurify.sanitize()` también acepta un nodo DOM (un `Element`, `DocumentFragment` o `Document`). Desde la versión 3.4.14 esa ruta está reforzada para nodos que no provienen del analizador HTML: un nodo construido con la API DOM o analizado como XML/XHTML (por ejemplo, mediante `DOMParser` con `application/xhtml+xml` e `importNode()`) puede portar nombres de atributos con mayúsculas preservadas como `ONERROR`, o un elemento rawtext como `<style>` con un elemento hijo o su propia etiqueta de cierre dentro de su texto. Ambas formas son invisibles para un sanitizador de cadenas porque el analizador HTML nunca puede construirlas, pero se escapan al reanalizarse. DOMPurify ahora elimina atributos por su nodo `Attr` exacto y trata estos árboles de texto literal como inseguros, de modo que mezclar contextos de documento en la entrada queda cubierto. Sigue siendo su responsabilidad no mezclar contextos en el lado de la _salida_, véase el párrafo anterior.

### Vale, tiene sentido, sigamos

Después de sanitizar su marcado, también puede echar un vistazo a la propiedad `DOMPurify.removed` y averiguar qué elementos y atributos fueron descartados. Por favor, **no use** esta propiedad para tomar decisiones críticas de seguridad. Es solo una pequeña ayuda para mentes curiosas.

### Ejecutar DOMPurify en el servidor

Técnicamente, DOMPurify también funciona del lado del servidor con Node.js. Nuestro soporte se esfuerza por seguir el [ciclo de versiones de Node.js](https://nodejs.org/en/about/previous-releases).

Ejecutar DOMPurify en el servidor requiere que haya un DOM presente, lo cual probablemente no sorprenda. Normalmente, [jsdom](https://github.com/jsdom/jsdom) es la herramienta de elección y **recomendamos encarecidamente** usar la última versión de _jsdom_.

¿Por qué? Porque se sabe que las versiones antiguas de _jsdom_ tienen errores que resultan en XSS _incluso si_ DOMPurify hace todo correctamente al 100%. Existen **vectores de ataque conocidos** en, por ejemplo, _jsdom v19.0.0_ que están corregidos en _jsdom v20.0.0_ - y por eso realmente recomendamos mantener _jsdom_ actualizado.

Tenga en cuenta también que existen herramientas como [happy-dom](https://github.com/capricorn86/happy-dom), pero **no se consideran seguras** en este momento. Actualmente no se recomienda combinar DOMPurify con _happy-dom_ y probablemente provoque XSS. Para conocer los antecedentes de por qué el DOM del lado del servidor que elija forma parte de su base de computación confiable, consulte [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).

En entornos de ejecución donde _jsdom_ no puede ejecutarse, como Cloudflare Workers o Vercel Edge, [purify-edge](https://github.com/anzal1/purify-edge) es un proyecto de terceros que ejecuta un DOMPurify sin modificar sobre una ventana basada en parse5. Nuestra suite de pruebas puede ejecutarse contra él con `npm run test:purify-edge` como comprobación de compatibilidad. No lo mantenemos nosotros, y una ejecución exitosa no constituye ni un respaldo ni una garantía de seguridad.

Aparte de eso, está bien usar DOMPurify en el servidor. Probablemente. Esto realmente depende de _jsdom_ o del DOM que utilice del lado del servidor. Si puede vivir con eso, así es como se hace funcionar:

```bash
npm install dompurify
npm install jsdom
```

Para _jsdom_ (utilice una versión actualizada), esto debería funcionar:

```js
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>');
```

O incluso esto, si prefieres trabajar con importaciones:

```js
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>');
```

Si tienes problemas para hacerlo funcionar en tu configuración específica, considera revisar el increíble proyecto [isomorphic-dompurify](https://github.com/kkomelin/isomorphic-dompurify), que resuelve muchos de los problemas con los que la gente podría encontrarse.

```bash
npm install isomorphic-dompurify
```

```js
import DOMPurify from 'isomorphic-dompurify';

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

## ¿Hay una demo?

¡Por supuesto que hay una demo! [Prueba DOMPurify](https://cure53.de/purify)

## ¿Y si encuentro un fallo de seguridad?

En primer lugar, ponte en contacto con nosotros de inmediato por [correo electrónico](mailto:[email protected]) para que podamos trabajar en una solución. [Clave PGP](https://keyserver.ubuntu.com/pks/lookup?op=vindex&search=0xC26C858090F70ADA)

Además, ¡probablemente seas elegible para una recompensa por errores! La buena gente de [Fastmail](https://www.fastmail.com/) usa DOMPurify en sus servicios y añadió nuestra biblioteca a su alcance de recompensas por errores. Así que, si encuentras una forma de eludir o debilitar DOMPurify, echa también un vistazo a su sitio web y a la [información sobre recompensas por errores](https://www.fastmail.com/about/bugbounty/).

## ¿Algunos ejemplos de saneamiento, por favor?

¿Cómo se ve el marcado saneado? Bueno, [la demo](https://cure53.de/purify) lo muestra para un gran conjunto de elementos maliciosos. ¡Pero también mostremos algunos ejemplos más pequeños!

```js
DOMPurify.sanitize(''); // becomes <img src="https://raw.githubusercontent.com/cure53/dompurify/main/x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abcdef</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="//google.com">click</a></li></ul>
```

Estos son solo una muestra. Para consultar la taxonomía completa de las clases de ataque de las que provienen estas muestras —mutation XSS, confusión de espacios de nombres, DOM clobbering, fugas de rawtext y más—, véase [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).

## ¿Qué es compatible?

DOMPurify actualmente es compatible con HTML5, SVG y MathML. DOMPurify permite por defecto CSS y atributos de datos personalizados de HTML. DOMPurify también es compatible con el Shadow DOM, y sanitiza las plantillas DOM de forma recursiva. Eso cubre únicamente las shadow roots abiertas: una shadow root cerrada no puede leerse desde el script, por lo que DOMPurify no puede ver ni sanitizar lo que hay dentro de ella. Las cadenas no se ven afectadas, porque el propio analizador de DOMPurify ignora las shadow roots declarativas (`<template shadowrootmode>`), pero `setHTMLUnsafe()` y `Document.parseHTMLUnsafe()` no lo hacen: si analizas marcado no confiable con ellos y luego pasas los nodos resultantes a DOMPurify (`IN_PLACE`, `RETURN_DOM`, `RETURN_DOM_FRAGMENT`), cualquier shadow root cerrada en ese marcado se devuelve sin sanitizar. En su lugar, pasa el marcado no confiable a DOMPurify como una cadena. DOMPurify también te permite sanitizar HTML para usarlo con la API `$()` de jQuery y `elm.html()` sin problemas conocidos. Para conocer el conjunto exacto de elementos y atributos permitidos por defecto, véase la página wiki [Default TAGs & ATTRIBUTEs allow-list & blocklist](https://github.com/cure53/DOMPurify/wiki/Default-TAGs-ATTRIBUTEs-allow-list-&-blocklist).

## ¿Qué pasa con los navegadores heredados como Internet Explorer?

DOMPurify no hace absolutamente nada. Simplemente devuelve exactamente la cadena que le proporcionaste. DOMPurify expone una propiedad llamada `isSupported`, que te indica si podrá realizar su trabajo, de modo que puedas idear tu propio plan de respaldo.

## ¿Qué pasa con DOMPurify y Trusted Types?

En la versión 1.0.9, se añadió a DOMPurify la compatibilidad con la [Trusted Types API](https://github.com/w3c/webappsec-trusted-types) ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API)).
En la versión 2.0.0, se añadió un indicador de configuración para controlar el comportamiento de DOMPurify al respecto.

Cuando se usa `DOMPurify.sanitize` en un entorno donde la Trusted Types API está disponible y `RETURN_TRUSTED_TYPE` está establecido en `true`, intenta devolver un valor `TrustedHTML` en lugar de una cadena (el comportamiento de las opciones de configuración `RETURN_DOM` y `RETURN_DOM_FRAGMENT` no cambia).

Ten en cuenta que, para crear una política en `trustedTypes` usando DOMPurify, se requiere `RETURN_TRUSTED_TYPE: false`, ya que `createHTML` espera una cadena normal, no `TrustedHTML`. El siguiente ejemplo lo muestra.

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

Cuando no se proporciona `TRUSTED_TYPES_POLICY`, DOMPurify intenta crear su propia política interna de Trusted Types llamada `dompurify`. Si tu página ya define su propia política junto con una CSP estricta (por ejemplo, `trusted-types my-organization`) que no permite una política llamada `dompurify`, este intento es bloqueado por el navegador y registra una advertencia `TrustedTypes policy dompurify could not be created.` junto con una violación de CSP.

Para evitar que DOMPurify cree su política de respaldo interna, pasa `TRUSTED_TYPES_POLICY: null`. Esta es la opción correcta cuando llamas a `DOMPurify.sanitize` desde dentro del `createHTML` de tu propia política, y significa que no tienes que añadir `dompurify` a la lista de permitidos `trusted-types` de tu CSP.

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

**No** pases tu propia política de envoltura de vuelta a DOMPurify como su `TRUSTED_TYPES_POLICY` (por ejemplo, mediante `DOMPurify.setConfig({ TRUSTED_TYPES_POLICY: myPolicy })`) cuando el `createHTML` de esa política ya llama a `DOMPurify.sanitize`. Eso es circular por definición —la sanitización llamaría a la política, que sanitiza llamando a DOMPurify de nuevo— y DOMPurify lanzará un `TypeError` descriptivo para evitar la recursión infinita. Tu propia política debería llamar a DOMPurify; DOMPurify no debería configurarse para llamar a tu política.

Si quieres que este patrón de política `default` se aplique automáticamente en toda una página —de modo que cada sink de HTML quede sanitizado, incluido el código heredado, los widgets de terceros y los miles de asignaciones a `innerHTML` que no puedes encontrar o reescribir fácilmente— echa un vistazo a [DOMFortify](https://github.com/cure53/DOMFortify). Instala exactamente ese tipo de política `default` de Trusted Types respaldada por DOMPurify y rechaza de plano los sinks de script (`eval`, `script.src`, ...). Es un proyecto deliberadamente separado: DOMPurify sigue siendo un sanitizador enfocado, y DOMFortify se encarga de la capa de aplicación a nivel de documento que queda intencionalmente fuera del alcance de DOMPurify.

## ¿Puedo configurar DOMPurify?

Sí. Los valores de configuración predeterminados incluidos ya son bastante buenos, pero por supuesto puedes sobrescribirlos. Consulta la carpeta [`/demos`](https://github.com/cure53/DOMPurify/tree/main/demos) para ver un montón de ejemplos sobre cómo [personalizar DOMPurify](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this).

Antes de ampliar la lista de permitidos (`ADD_TAGS`, `ADD_ATTR`, `CUSTOM_ELEMENT_HANDLING`, …) o relajar un valor predeterminado, vale la pena revisar las [etiquetas y atributos sobre los que conviene pensarlo dos veces](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model#dangerous-tags-and-attributes-think-twice-before-allow-listing): algunos son peligrosos de formas poco evidentes.

### Configuración general

```js
// 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 });
```

### Controlar nuestras listas de permitidos y bloqueados

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

// note: while <table> is allowed, <tbody> is always allowed too and cannot be
// forbidden - browsers insert it on their own, and forbidding it used to make
// sanitize() loop (see #365). Forbid 'table' as well to drop tables entirely.

// 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 del comportamiento relacionado con Custom Elements

```js
// 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>
```

### Comportamiento de control relacionado con valores URI

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

### Controlar los valores de atributo permitidos

```js
// 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|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
// The example below extends the default with one additional scheme (sftp).
// Keep the pattern linear-time: it runs against attacker-controlled values.
const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_URI_REGEXP:
    /^(?:(?:(?:f|ht)tps?|sftp|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
});
```

### Influir en el tipo de retorno

```js
// 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 });
```

### Influye en cómo saneamos

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

### Influir en dónde saneamos

```js
// 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
```

Algunas cosas que debes saber sobre `IN_PLACE`:

- El nodo raíz que pasas debe ser en sí mismo una etiqueta permitida y no debe estar afectado por DOM-clobbering (por ejemplo, un `<form>` con un hijo llamado `nodeName` u `ownerDocument`). Si lo está, DOMPurify elimina del subárbol de la raíz todos los atributos que no están en la lista de permitidos y luego lanza un `TypeError`, de modo que una raíz rechazada nunca se devuelve armada.
- Si algo lanza una excepción a mitad del recorrido, la misma neutralización de fallo cerrado se ejecuta sobre la raíz y sobre cada subárbol ya desvinculado durante ese recorrido antes de que el error se propague.
- Los nodos que un hook desvincula del árbol (un patrón común, consulta [Hooks](#hooks)) se tratan como eliminados. En modo `IN_PLACE`, todo elemento que estaba bajo la raíz cuando comenzó `sanitize()` y ya no está bajo ella cuando la llamada termina tiene sus atributos no permitidos eliminados antes de que `sanitize()` retorne o lance una excepción, sin importar qué lo desvinculó: un hook que elimina el nodo para el que fue llamado, su padre u otro ancestro, o un nodo en otra parte del árbol, un hook que mueve un subárbol fuera de la raíz, o un elemento personalizado que reacciona a una de las propias eliminaciones de atributos de DOMPurify. Así, un `` que ya se estaba cargando cuando construiste el árbol en vivo no puede dispararse después de que `sanitize()` retorne. Del mismo modo, un nodo de tu árbol que un hook o elemento personalizado mueve a una posición por la que el recorrido ya pasó sigue siendo saneado antes de que `sanitize()` retorne; si el árbol sigue cambiando de esa manera, DOMPurify despoja la raíz por completo y lanza una excepción en lugar de devolverla.
- DOMPurify no puede deshacer mutaciones del motor que ya se dispararon _antes_ de que se llamara a `sanitize()` (un parche aplicado al conectar, un reclonado de `selectedcontent`, etc.). Sanea los árboles controlados por el atacante antes de conectarlos al documento en vivo, no después.

---

[Read more](https://github.com/cure53/dompurify)
Descargar herramienta