# sanitize-html
[](https://circleci.com/gh/apostrophecms/sanitize-html/tree/main)
`sanitize-html` provides a simple HTML sanitizer with a clear API.
`sanitize-html` is tolerant. It is well suited for cleaning up HTML fragments such as those created by ckeditor and other rich text editors. It is especially handy for removing unwanted CSS when copying and pasting from Word.
`sanitize-html` allows you to specify the tags you want to permit, and the permitted attributes for each of those tags.
If a tag is not permitted, the contents of the tag are not discarded. There are
some exceptions to this, discussed below in the "Discarding the entire contents
of a disallowed tag" section.
The syntax of poorly closed `p` and `img` elements is cleaned up.
`href` attributes are validated to ensure they only contain `http`, `https`, `ftp` and `mailto` URLs. Relative URLs are also allowed. Ditto for `src` attributes.
Allowing particular urls as a `src` to an iframe tag by filtering hostnames is also supported.
HTML comments are not preserved.
## Requirements
`sanitize-html` is intended for use with Node. That's pretty much it. All of its npm dependencies are pure JavaScript. `sanitize-html` is built on the excellent `htmlparser2` module.
## How to use
### Browser
*Think first: why do you want to use it in the browser?* Remember, *servers must never trust browsers.* You can't sanitize HTML for saving on the server anywhere else but on the server.
But, perhaps you'd like to display sanitized HTML immediately in the browser for preview. Or ask the browser to do the sanitization work on every page load. You can if you want to!
* Clone repository
* Run npm install and build / minify:
```bash
npm install
npm run minify
```
You'll find the minified and unminified versions of sanitize-html (with all its dependencies included) in the dist/ directory.
Use it in the browser:
```html
some text...
``` We can do that with the following filter: ```js sanitizeHtml( 'some text...
', { textFilter: function(text, tagName) { if (['a'].indexOf(tagName) > -1) return //Skip anchor tags return text.replace(/\.\.\./, '…'); } } ); ``` Note that the text passed to the `textFilter` method is already escaped for safe display as HTML. You may add markup and use entity escape sequences in your `textFilter`. ### Iframe Filters If you would like to allow iframe tags but want to control the domains that are allowed through you can provide an array of hostnames and(or) array of domains that you would like to allow as iframe sources. This hostname is a property in the options object passed as an argument to the `sanitize-html` function. These arrays will be checked against the html that is passed to the function and return only `src` urls that include the allowed hostnames or domains in the object. The url in the html that is passed must be formatted correctly (valid hostname) as an embedded iframe otherwise the module will strip out the src from the iframe. Make sure to pass a valid hostname along with the domain you wish to allow, i.e.: ```js allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], allowedIframeDomains: ['zoom.us'] ``` You may also specify whether or not to allow relative URLs as iframe sources. ```js allowIframeRelativeUrls: true ``` Note that if unspecified, relative URLs will be allowed by default if no hostname or domain filter is provided but removed by default if a hostname or domain filter is provided. **Remember that the `iframe` tag must be allowed as well as the `src` attribute.** For example: ```js clean = sanitizeHtml('', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] }); ``` will pass through as safe whereas: ```js clean = sanitizeHtml('
', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] }); ``` or ```js clean = sanitizeHtml('
', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] }); ``` will return an empty iframe tag. If you want to allow any subdomain of any level you can provide the domain in `allowedIframeDomains` ```js clean = sanitizeHtml('
', {
allowedTags: [ 'p', 'em', 'strong', 'iframe' ],
allowedClasses: {
'p': [ 'fancy', 'simple' ],
},
allowedAttributes: {
'iframe': ['src']
},
allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'],
allowedIframeDomains: ['zoom.us']
});
```
will pass through as safe.
### Allowed CSS Classes
If you wish to allow specific CSS classes on a particular element, you can do so with the `allowedClasses` option. Any other CSS classes are discarded.
This implies that the `class` attribute is allowed on that element.
```js
// Allow only a restricted set of CSS classes and only on the p tag
clean = sanitizeHtml(dirty, {
allowedTags: [ 'p', 'em', 'strong' ],
allowedClasses: {
'p': [ 'fancy', 'simple' ]
}
});
```
### Allowed CSS Styles
If you wish to allow specific CSS _styles_ on a particular element, you can do that with the `allowedStyles` option. Simply declare your desired attributes as regular expression options within an array for the given attribute. Specific elements will inherit whitelisted attributes from the global (\*) attribute. Any other CSS classes are discarded.
**You must also use `allowedAttributes`** to activate the `style` attribute for the relevant elements. Otherwise this feature will never come into play.
**When constructing regular expressions, don't forget `^` and `$`.** It's not enough to say "the string should contain this." It must also say "and only this."
**URLs in inline styles are NOT filtered by any mechanism other than your regular expression.**
```js
clean = sanitizeHtml(dirty, {
allowedTags: ['p'],
allowedAttributes: {
'p': ["style"],
},
allowedStyles: {
'*': {
// Match HEX and RGB
'color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/],
'text-align': [/^left$/, /^right$/, /^center$/],
// Match any number with px, em, or %
'font-size': [/^\d+(?:px|em|%)$/]
},
'p': {
'font-size': [/^\d+rem$/]
}
}
});
```
### Allowed URL schemes
By default we allow the following URL schemes in cases where `href`, `src`, etc. are allowed:
```js
[ 'http', 'https', 'ftp', 'mailto' ]
```
You can override this if you want to:
```js
sanitizeHtml(
// teeny-tiny valid transparent GIF in a data URL
'',
{
allowedTags: [ 'img', 'p' ],
allowedSchemes: [ 'data', 'http' ]
}
);
```
You can also allow a scheme for a particular tag only:
```js
allowedSchemes: [ 'http', 'https' ],
allowedSchemesByTag: {
img: [ 'data' ]
}
```
And you can forbid the use of protocol-relative URLs (starting with `//`) to access another site using the current protocol, which is allowed by default:
```js
allowProtocolRelative: false
```
### Discarding the entire contents of a disallowed tag
Normally, with a few exceptions, if a tag is not allowed, all of the text within it is preserved, and so are any allowed tags within it.
The exceptions are:
`style`, `script`, `textarea`, `option`
If you wish to replace this list, for instance to discard whatever is found
inside a `noscript` tag, use the `nonTextTags` option:
```js
nonTextTags: [ 'style', 'script', 'textarea', 'option', 'noscript' ]
```
Note that if you use this option you are responsible for stating the entire list. This gives you the power to retain the content of `textarea`, if you want to.
The content still gets escaped properly, with the exception of the `script` and
`style` tags. *Allowing either `script` or `style` leaves you open to XSS
attacks. Don't do that* unless you have good reason to trust their origin.
sanitize-html will log a warning if these tags are allowed, which can be
disabled with the `allowVulnerableTags: true` option.
### Choose what to do with disallowed tags
Instead of discarding, or keeping text only, you may enable escaping of the entire content:
```js
disallowedTagsMode: 'escape'
```
This will transform `