Sanitizer()

Draft

This page is not complete.

Secure context

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The Sanitizer() constructor creates a new sanitizer object which allows developers to take untrusted strings of HTML, and sanitize them for safe insertion into a document’s DOM.

Syntax

var sanitizer = new Sanitizer();

Parameters

config Optional
An object in the format of SanitizerConfig. Options are as follows:
  • allowElements: An Array of strings representing elements the sanitizer should retain in the input.
  • blockElements: An Array of strings representing elements the sanitizer should remove in the input, but retain any of their children elements.
  • dropElements: An Array of strings representing elements the sanitizer should remove in the input along with their children.
  • allowAttributes: An Array of strings representing attributes the sanitizer should retain in the input.
  • dropAttributes: An Array of strings representing attributes the sanitizer should remove in the input.

At the time of writing the default elements within each configuration property above are still under consideration. Due to this the above config parameter has not been implemented.

Examples

This example shows the result of sanitizing a string with disallowed script elements.

new Sanitizer().sanitizeToString("abc <script>alert(1)</script> def");
// Result: script will be removed: "abc alert(1) def"

This example shows how the different configuration options would return the same string.

const sample = "Some text <b><i>with</i></b> <blink>tags</blink>.";

const allow = new Sanitizer({allowElements: [ "b" ]).sanitizeToString(sample);
console.log(allow)
// Logs: "Some text <b>with</b> text tags."

const block = new Sanitizer({blockElements: [ "b" ]).sanitizeToString(sample);
console.log(block);
// Logs: "Some text <i>with</i> <blink>tags</blink>."

const drop = new Sanitizer({dropElements: [ "b" ]).sanitizeToString(sample);
// Logs: "Some text tags."

Specifications

Specification Status Comment
HTML Sanitizer API
The definition of 'sanitizer' in that specification.
Working Draft Initial definition.

Browser compatibility

BCD tables only load in the browser