### Install sanitize-html for Node.js Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Install the sanitize-html package using npm for use in a Node.js environment. ```bash npm install sanitize-html ``` -------------------------------- ### Install TypeScript Types for sanitize-html Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Install the community-supported TypeScript definitions for sanitize-html. Ensure your tsconfig.json has esModuleInterop=true or use the alternative import method. ```bash npm install -D @types/sanitize-html ``` -------------------------------- ### Install TypeScript Types Source: https://www.npmjs.com/package/sanitize-html?activeTab=readme Install the community-supported typing definition for TypeScript. Ensure esModuleInterop is set to true in tsconfig.json or use the alternative import method. ```bash npm install -D @types/sanitize-html ``` ```typescript import * as sanitizeHtml from 'sanitize-html'; ``` -------------------------------- ### Install sanitize-html for Browser Usage Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Install the sanitize-html package using npm or yarn. This package is intended to be included in your project's build process (e.g., webpack) for browser use. ```bash npm install sanitize-html ``` ```bash yarn add sanitize-html ``` -------------------------------- ### Allow CSS classes with a prefix using wildcard Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use the `*` wildcard in `allowedClasses` to permit classes that start with a specific prefix for a given tag. ```javascript allowedClasses: { 'code': [ 'language-*', 'lang-*' ], '*': [ 'fancy', 'simple' ] } ``` -------------------------------- ### Allow attributes with a prefix using wildcard Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use the `*` wildcard to allow all attributes starting with a specific prefix for a given tag. ```javascript allowedAttributes: { a: [ 'href', 'data-*' ] } ``` -------------------------------- ### Allow URL Schemes for Specific Tags Source: https://www.npmjs.com/package/sanitize-html?activeTab=readme Define allowed URL schemes on a per-tag basis. This example permits 'data' schemes specifically for `img` tags, while other tags adhere to the general `allowedSchemes` list. ```javascript allowedSchemesByTag: { img: [ 'data' ] } ``` -------------------------------- ### Advanced Filtering with Event Hooks Source: https://www.npmjs.com/package/sanitize-html?activeTab=code Implement advanced HTML filtering by using `onOpenTag`, `onCloseTag`, and `textFilter` event hooks. This example demonstrates adding spaces around removed tags by tracking tag states and modifying text content. ```javascript const allowedTags = [ 'b' ]; let addSpace = false; const sanitizedHtml = sanitizeHtml( 'There should be
spaces
', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], allowedIframeDomains: ['zoom.us'] }); ``` -------------------------------- ### Disallow Iframes with Non-Matching Domains Source: https://www.npmjs.com/package/sanitize-html?activeTab=readme Similar to hostnames, if an iframe's `src` domain does not match any in `allowedIframeDomains`, the `src` will be removed. This example shows a Vimeo URL with a non-matching domain. ```javascript const clean = sanitizeHtml('
', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] }); ``` -------------------------------- ### Advanced Filtering with Event Hooks Source: https://www.npmjs.com/package/sanitize-html?activeTab=readme Implement custom filtering logic by hooking into `onOpenTag`, `onCloseTag`, and `textFilter` events. This example adds spaces around disallowed tags by using flags set during tag events and modifying text content. ```javascript const allowedTags = [ 'b' ]; let addSpace = false; const sanitizedHtml = sanitizeHtml( 'There should be
spaces
spaces
', {
allowedTags: [ 'p', 'em', 'strong', 'iframe' ],
allowedClasses: {
'p': [ 'fancy', 'simple' ],
},
allowedAttributes: {
'iframe': ['src']
},
allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com']
});
```
--------------------------------
### Default Allowed URL Schemes
Source: https://www.npmjs.com/package/sanitize-html?activeTab=readme
This array lists the default URL schemes that are permitted when attributes like `href` or `src` are allowed. Common schemes like http, https, ftp, and mailto are included.
```javascript
[ 'http', 'https', 'ftp', 'mailto' ]
```
--------------------------------
### Allow CSS classes using regular expressions
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Configure allowed CSS classes using regular expressions. It is advised to anchor expressions with `^` for prefix matching.
```javascript
allowedClasses: {
p: [ /^regex\d{2}$/ ]
}
```
--------------------------------
### Allow specific attributes for any tag using wildcard
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Use the `*` wildcard as a tag name to apply a list of attributes to all tags.
```javascript
allowedAttributes: {
'*': [ 'href', 'align', 'alt', 'center', 'bgcolor' ]
}
```
--------------------------------
### Allow CSS Classes with Wildcards or Regex
Source: https://www.npmjs.com/package/sanitize-html?activeTab=code
Configure `allowedClasses` to permit classes matching a prefix wildcard or a regular expression. Using `*` as a tag name allows the specified classes on any tag.
```javascript
allowedClasses: {
'code': [ 'language-*', 'lang-*' ],
'*': [ 'fancy', 'simple' ]
}
```
```javascript
allowedClasses: {
p: [ /^regex\d{2}$/ ]
}
```
--------------------------------
### Import sanitize-html with TypeScript (esModuleInterop=false)
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
When esModuleInterop is not enabled in tsconfig.json, import sanitize-html using a namespace import.
```typescript
import * as sanitizeHtml from 'sanitize-html';
```
--------------------------------
### Import sanitize-html in Node.js (CommonJS)
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Import the sanitize-html module in a CommonJS environment.
```javascript
// Or in CommonJS
const sanitizeHtml = require('sanitize-html');
```
--------------------------------
### Forbid Protocol-Relative URLs
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Set `allowProtocolRelative` to `false` to prevent the use of protocol-relative URLs (e.g., `//example.com`). This ensures a specific protocol is always used.
```javascript
allowProtocolRelative: false
```
--------------------------------
### Allow Custom URL Schemes
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Override the default allowed URL schemes or add new ones like 'data' using `allowedSchemes`. This is useful for data URLs or custom protocols.
```javascript
sanitizeHtml(
// teeny-tiny valid transparent GIF in a data URL
'',
{
allowedTags: [ 'img', 'p' ],
allowedSchemes: [ 'data', 'http' ]
}
);
```
--------------------------------
### Import sanitize-html in Node.js (ES Modules)
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Import the sanitize-html module in an ES module environment.
```javascript
// In ES modules
import sanitizeHtml from 'sanitize-html';
```
--------------------------------
### Allow specific values for attributes
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Configure specific allowed values for an attribute using an object with a `values` array. Set `multiple: true` to allow multiple values separated by spaces.
```javascript
allowedAttributes: {
iframe: [
{
name: 'sandbox',
multiple: true,
values: ['allow-popups', 'allow-same-origin', 'allow-scripts']
}
]
}
```
--------------------------------
### Allow Script Tags on Specific Hostnames
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Configure `allowedScriptHostnames` to allow script tags from a precise list of hostnames. This offers finer control than domain-based filtering.
```javascript
const clean = sanitizeHtml('', {
allowedTags: ['script'],
allowedAttributes: {
script: ['src']
},
allowedScriptHostnames: [ 'www.authorized.com' ],
})
```
--------------------------------
### Handle Invalid Iframe Sources
Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies
Demonstrates how sanitize-html strips the 'src' attribute from iframes with disallowed hostnames, resulting in an empty tag.
```javascript
const clean = sanitizeHtml('
', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], }, allowedAttributes: { 'iframe': ['src'] }, allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] }); ``` -------------------------------- ### Allow Custom URL Schemes Per Tag Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Specify allowed URL schemes on a per-tag basis using `allowedSchemesByTag`. This provides granular control over which schemes are permitted for specific elements. ```javascript allowedSchemes: [ 'http', 'https' ], allowedSchemesByTag: { img: [ 'data' ] } ``` -------------------------------- ### Custom htmlparser2 Options Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Pass custom options to the underlying `htmlparser2` library using the `parser` option. Be cautious, as changing default settings like `decodeEntities: false` can introduce security risks. ```javascript const clean = sanitizeHtml(dirty, { allowedTags: ['a'], parser: { lowerCaseTags: true } }); ``` -------------------------------- ### Transforming Tags: Wildcard and Helper Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies The `*` wildcard can be used to transform all tags. The `simpleTransform` helper simplifies changing a tag and/or adding attributes. The `shouldMerge` parameter controls whether existing attributes are preserved. ```javascript const clean = sanitizeHtml(dirty, { transformTags: { 'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}), } }); ``` -------------------------------- ### Basic HTML Sanitization in Node.js Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Sanitize an HTML string using the default allowed tags and attributes provided by sanitize-html. ```javascript const dirty = 'some really tacky HTML'; const clean = sanitizeHtml(dirty); ``` -------------------------------- ### Import sanitize-html in Node.js Source: https://www.npmjs.com/package/sanitize-html?activeTab=code Import the sanitize-html module in Node.js using either ES modules or CommonJS syntax. ```javascript // In ES modules import sanitizeHtml from 'sanitize-html'; // Or in CommonJS const sanitizeHtml = require('sanitize-html'); ``` -------------------------------- ### Default sanitize-html Options Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies This object represents the default configuration for sanitize-html, specifying allowed HTML tags, attributes, and other parsing behaviors. It's useful for understanding the library's baseline security settings. ```javascript allowedTags: [ "address", "article", "aside", "footer", "header", "h1", "h2", "h3", "h4", "h5", "h6", "hgroup", "main", "nav", "section", "blockquote", "dd", "div", "dl", "dt", "figcaption", "figure", "hr", "li", "main", "ol", "p", "pre", "ul", "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", "em", "i", "kbd", "mark", "q", "rb", "rp", "rt", "rtc", "ruby", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", "caption", "col", "colgroup", "table", "tbody", "td", "tfoot", "th", "thead", "tr" ], nonBooleanAttributes: [ 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', 'blocking', 'charset', 'cite', 'class', 'color', 'cols', 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'name', 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap', // Event handlers 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', 'onrejectionhandled', 'onscroll', 'onscrollend', 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', 'onvolumechange', 'onwaiting', 'onwheel' ], disallowedTagsMode: 'discard', allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but // these attributes would make sense if we did. img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], // URL schemes we permit allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ], allowedSchemesByTag: {}, allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], allowProtocolRelative: true, enforceHtmlBoundary: false, parseStyleAttributes: true ``` -------------------------------- ### Allow All Tags or Attributes Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies To permit all HTML tags or attributes, set `allowedTags` or `allowedAttributes` to `false` respectively. This bypasses the default filtering for the specified option. ```javascript allowedTags: false, allowedAttributes: false ``` -------------------------------- ### Add a Tag to Allowed Tags Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Extend the default allowed tags by concatenating a new tag to the existing list. This is useful when you need to permit a specific tag not included in the default set. ```javascript const clean = sanitizeHtml(dirty, { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) }); ``` -------------------------------- ### Disallow all tags and attributes Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies To disallow all HTML tags and attributes, set `allowedTags` to an empty array and `allowedAttributes` to an empty object. ```javascript allowedTags: [], allowedAttributes: {} ``` -------------------------------- ### Allow Script Tags on Specific Domains Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use `allowedScriptDomains` to permit script tags only from a list of specified domains. This helps mitigate XSS risks by restricting script sources. ```javascript const clean = sanitizeHtml('', { allowedTags: ['script'], allowedAttributes: { script: ['src'] }, allowedScriptDomains: ['authorized.com'], }) ``` -------------------------------- ### Set Disallowed Tags Mode to Completely Discard Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Employ `disallowedTagsMode: 'completelyDiscard'` to remove both the disallowed tag and all its content. This is useful for stripping out entire sections of potentially harmful HTML. ```javascript disallowedTagsMode: 'completelyDiscard' ``` -------------------------------- ### Allow Empty Non-Boolean Attributes Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies To allow empty values for all non-boolean attributes, set `nonBooleanAttributes` to an empty array. This can be useful for specific scenarios but may break standard attribute behavior. ```javascript nonBooleanAttributes: [] ``` -------------------------------- ### Define Non-Text Tags Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Customize the list of tags whose content should be discarded by default using `nonTextTags`. This includes tags like `style` and `script`. ```javascript nonTextTags: [ 'style', 'script', 'textarea', 'option', 'xmp', 'noscript' ] ``` -------------------------------- ### Advanced Tag Transformation with Custom Logic Source: https://www.npmjs.com/package/sanitize-html?activeTab=code Perform advanced tag transformations by providing a function to `transformTags`. This function receives the tag name and attributes, and can return a new tag name, attributes, or text content. ```javascript const clean = sanitizeHtml(dirty, { transformTags: { 'ol': function(tagName, attribs) { // My own custom magic goes here return { tagName: 'ul', attribs: { class: 'foo' } }; } } }); ``` ```javascript const clean = sanitizeHtml(dirty, { transformTags: { 'a': function(tagName, attribs) { return { tagName: 'a', text: 'Some text' }; } } }); ``` -------------------------------- ### Limit HTML Nesting Depth Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use the `nestingLimit` option to restrict the maximum depth of nested HTML tags. Tags exceeding this limit are stripped while preserving text content. ```javascript nestingLimit: 6 ``` -------------------------------- ### Allow specific CSS classes on a tag Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use the `allowedClasses` option to specify a list of allowed CSS classes for a particular tag. This also implicitly allows the `class` attribute on that tag. ```javascript // Allow only a restricted set of CSS classes and only on the p tag const clean = sanitizeHtml(dirty, { allowedTags: [ 'p', 'em', 'strong' ], allowedClasses: { 'p': [ 'fancy', 'simple' ] } }); ``` -------------------------------- ### Set Disallowed Tags Mode to Escape Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Use `disallowedTagsMode: 'escape'` to transform disallowed tags into HTML entities, preventing them from rendering but keeping their content visible as text. ```javascript disallowedTagsMode: 'escape' ``` -------------------------------- ### Remove All Empty Attributes Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies To remove all empty attributes, including valid ones, set `nonBooleanAttributes` to `['*']`. Use this option with caution as it can affect common valid attributes like `checked` or `selected`. ```javascript nonBooleanAttributes: ['*'] ``` -------------------------------- ### Set Disallowed Tags Mode to Recursive Escape Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Utilize `disallowedTagsMode: 'recursiveEscape'` to escape disallowed tags and all their nested content, ensuring that even allowed inner tags are escaped. ```javascript disallowedTagsMode: `recursiveEscape` ``` -------------------------------- ### Enforcing HTML Boundary Source: https://www.npmjs.com/package/sanitize-html?activeTab=dependencies Set `enforceHtmlBoundary` to `true` to discard any characters that appear outside the main `` tags. This is useful for cleaning up content from some text editors. ```javascript enforceHtmlBoundary: true ```