What is a Simple HTML Sanitizer in JavaScript?
Sanitizer API takes an untrusted string. Then remove the unwanted elements to sanitize the string and in the end, put sanitized elements in the document DOM. The sanitizer constructor is first created then its instance is configured. This configured parameter allows the user to enable custom elements and comments.
The “sanitizer” has three main methods for sanitizing untrusted strings:
- “Element.setHTML()” is the safer form of inner.html, it inserts the string as a child after sanitizing and parsing.
- “Sanitizer.sanitizeFor()” sanitizes the element in advance before the need to insert it in the DOM.
- “Sanitizer.sanitize()” sanitizes the frame that is available in the Document fragment(a document that has no parent).
How to Use the Element.setHTML() Method?
The “Element.setHTML” method works just like the “inner.html” element. There is only a little difference. The inner.HTML is just used for displaying elements on the screen. In the case of the “setHTML()” method, it offers “parsing” and “sanitizing” of the string to remove unwanted/faulty data.
Syntax
In the above syntax,
- The “string” parameter is a variable that contains the untrusted or unsanitized string.
- The “sanitizer” parameter contains the method which is used to sanitize the string.
- In the “setHTML( )” method, the string gets placed in the DOM.
Example of Sanitizer in JavaScript
In the below code snippet, the unsanitized string is converted into the sanitized form using the “Element.setHTML()” method:
The description of the above code is:
- First, create an “<h2>” tag to display a sanitized string and assign it an id of “display”.
- After that, create two constant type variables, the first one stores the “un-sanitized” string. The second one holds the object “sanitizer” of the sanitizer method.
- Then, the “target” variable is created which stores the location of the HTML element on which the string was placed after the sanitization process.
The output of the above code is:
The output confirms that unwanted tags are removed from the strings.
Note: Although there are three methods to sanitize in JavaScript. However, the remaining two methods ( sanitize and sanitizeFor ) are not compatible with any browser.
Conclusion
HTML sanitizer is used to sanitize the strings from unwanted tags, comments, or elements. It is used with the “setHTML()” method which helps in the parsing and sanitizing process and then inserts the new string in the DOM. This article has successfully demonstrated HTML sanitizer in JavaScript.