
Sanitizing user-generated content is crucial to prevent XSS attacks.
The most common types of attacks are cross-site scripting (XSS) and cross-site request forgery (CSRF).
To avoid these attacks, you should allow only specific HTML tags and attributes in your sanitizer.
For example, allowing the "img" tag is safe, but allowing the "script" tag can be a security risk.
A good sanitizer should also remove any unnecessary or malicious attributes from allowed tags.
Recommended read: How to Make Website with Html and Css
Sanitizing HTML Strings
Sanitizing HTML strings is a crucial step in preventing XSS attacks. The Sanitizer API provides safe methods for injecting HTML strings into an Element or a ShadowRoot.
The safe methods are Element.setHTML(), ShadowRoot.setHTML(), and Document.parseHTML(). These methods always remove XSS-unsafe elements and attributes.
The Sanitizer API also provides unsafe methods for injecting HTML strings, which are Element.setHTMLUnsafe(), ShadowRoot.setHTMLUnsafe(), and Document.parseHTMLUnsafe(). These methods use whatever sanitizer configuration is passed as an argument.
If no sanitizer is passed, the unsafe methods will inject all HTML elements and attributes allowed by the context. This is similar to using Element.innerHTML, but with additional safety features.
Suggestion: Html Safe Fonts
You can use the Sanitizer API to sanitize HTML strings with vanilla JS, but it's recommended to use a dedicated library like DOMPurify.
Here are some common tags allowed by the default sanitizer:
- a
- abbr
- b
- blockquote
- body
- br
- center
- code
- div
- em
- font
- h1
- h2
- h3
- h4
- h5
- h6
- hr
- i
- img
- label
- li
- ol
- p
- pre
- small
- source
- span
- strong
- table
- tbody
- tr
- td
- th
- thead
- ul
- u
- video
Remember, the safe methods should be used instead of Element.innerHTML, Element.outerHTML, or ShadowRoot.innerHTML for injecting untrusted HTML content.
Third Party Libraries
DOMPurify is a popular third-party library used for sanitizing HTML. It's a DOM-only, super-fast, and uber-tolerant XSS sanitizer.
DOMPurify was started in February 2014 and has since reached version v3.2.7. It's written in JavaScript and works in all modern browsers.
Developers used to rely on third-party libraries like DOMPurify for filtering input strings. However, the Sanitizer API is now integrated with the browser and is more aware of the parsing context.
The Sanitizer API can be used in the same places as DOMPurify, but is likely to be less efficient to use and reuse. DOMPurify is very simple to use and get started with.
DOMPurify doesn't break on MSIE or other legacy browsers, it simply does nothing. However, note that DOMPurify v2.5.8 is the latest version supporting MSIE.
Recommended read: Is Html Used to Create Web Pages
Configuration and Setup
You can configure DOMPurify by overriding its default configuration values, which are already quite good. Check out the /demos folder for examples on how to customize DOMPurify.
The Trusted Types API provides a way to ensure inputs are passed through a user-specified transformation function before being passed to an API that might execute that input. This transformation function is often used for sanitization.
You can configure a sanitizer configuration using either the SanitizerConfig or Sanitizer interface. SanitizerConfig is a dictionary object that defines arrays of elements or attributes that are allowed or disallowed, while Sanitizer is a wrapper around SanitizerConfig that provides methods to add and remove entities from the configuration.
Here are some options you can configure in DOMPurify:
- SAFE_FOR_JQUERY (since 2.1.0): No replacement required.
Security and Best Practices
Using a js html sanitizer is crucial for preventing cross-site scripting (XSS) attacks, which can occur when malicious code is injected into a website.
Always use a reputable library like DOMPurify or js-xss-sanitizer, which have been extensively tested and proven to be effective against XSS attacks.
Readers also liked: Html Sanitizer
When sanitizing user input, make sure to remove all HTML tags, including script and style tags, to prevent any potential code injection.
Regularly update your sanitizer library to ensure you have the latest security patches and features.
By following these best practices, you can significantly reduce the risk of XSS attacks and keep your users' data safe.
Foot Gun Potential?
Sanitizing HTML is not a one-time task, it's a process that requires careful consideration to avoid voiding its effects. If you first sanitize HTML and then modify it afterwards, you might easily void the effects of sanitization.
Some libraries may mess around with the HTML on their own, even after sanitization. If you're using a library that does this, make sure to check its documentation to see if it's safe to use after sanitization.
Suggestion: Html B Tag
What If I Find a Security Bug?
If you find a security bug, you might be eligible for a bug bounty.
Fastmail uses DOMPurify for their services and has added our library to their bug bounty scope, so it's worth checking their website for more information.
Relevant commits will be signed with the key 0x24BB6BF4 for additional security, starting from the 8th of April 2016.
But Why?
Users often copy-paste awful HTML generated by MS Word, MS Outlook or Apple Mail that needs a clean-up.
This is because these applications tend to add excessive and unnecessary HTML tags to the text.
Users need to remove excessive formatting in a WYSIWYG editor.
This can be a time-consuming task, especially when dealing with complex documents.
You simply need to ease the load in the server-side sanitizer.
By sanitizing the input on the client-side, you can reduce the load on your server and make your application more efficient.
Many other use-cases require a front-end HTML sanitizer, such as displaying an (ugly) email message in a (beautiful) mobile app.
Consider reading: Html Side
Performance and Benchmarks
Js Html Sanitizer is a game-changer when it comes to speed and performance.
It uses the browser/DOM to parse HTML, which makes it significantly faster than "pure JavaScript" sanitizers.
This approach allows it to sanitize the HTML at an incredible rate of ~370 times per second on an i5 core CPU in Firefox Quantum.
The benchmark.js test on the BBC homepage confirms this impressive speed, making it a top choice for developers.
In comparison, HtmlSanitizer outperforms DOMPurify in benchmark testing.
Development and Contributing
DOMPurify is an open-source JavaScript library for sanitizing and cleaning HTML. Many people have contributed to its development over the years.
Cybozu and other organizations have financially supported the project, helping it grow and improve. Their contributions are greatly appreciated.
The library has a large and active community, with many developers contributing code and feedback. This community-driven approach has helped DOMPurify become a robust and reliable tool.
DOMPurify has been used in various projects and applications, including those developed by Healthchecks and Sentry. These companies have helped test and improve the library.
The project's GitHub repository shows a long list of contributors, including individuals and organizations. They have all played a role in making DOMPurify what it is today.
DOMPurify's contributors come from a variety of backgrounds and locations, demonstrating the project's global reach and appeal.
A unique perspective: How to Add Svg to Html Project
Lit-Node Specifics
You can use Element.setHTML(), ShadowRoot.setHTML(), and Document.parseHTML() for injecting HTML strings into an Element or a ShadowRoot, and for parsing HTML into a Document. These methods are safe and will remove XSS-unsafe elements and attributes.
For another approach, see: Langchain Document Loaders Html

The safe methods are context aware and will drop any elements that the HTML specification does not allow in the target element.
If you need to inject untrusted HTML content, you should use the safe methods instead of Element.innerHTML, Element.outerHTML, or ShadowRoot.innerHTML.
You can use a custom sanitizer configuration to filter out specific HTML entities from the input before it is injected.
Here are the safe methods:
- Element.setHTML()
- ShadowRoot.setHTML()
- Document.parseHTML()
These methods take the HTML to be injected and an optional sanitizer configuration as arguments.
If no sanitizer is passed as a parameter, the safe methods will use the default sanitizer configuration, which allows all elements and attributes except those that are known to be unsafe.
If you want to create a custom sanitizer, you can use the Sanitizer() constructor and specify a SanitizerConfig that allows specific elements and attributes.
For example, you can use allowElement() to allow specific elements, allowAttribute() to allow specific attributes, and replaceElementWithChildren() to replace specific elements with their inner content.
Featured Images: pexels.com

