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
-
configOptional -
An object in the format of SanitizerConfig. Options are as follows:
-
allowElements: AnArrayofstringsrepresenting elements the sanitizer should retain in the input. -
blockElements: AnArrayofstringsrepresenting elements the sanitizer should remove in the input, but retain any of their children elements. -
dropElements: AnArrayofstringsrepresenting elements the sanitizer should remove in the input along with their children. -
allowAttributes: AnArrayofstringsrepresenting attributes the sanitizer should retain in the input. -
dropAttributes: AnArrayofstringsrepresenting attributes the sanitizer should remove in the input.
-
Note: 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 |
|---|
| HTML Sanitizer API # dom-sanitizer-sanitizer |
Browser compatibility
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
Sanitizer |
93 |
93 |
83 |
No |
79 |
No |
No |
No |
No |
No |
No |
No |
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Sanitizer/Sanitizer