# Sanitize Sanitize is an allowlist-based HTML and CSS sanitizer. It removes all HTML and/or CSS from a string except the elements, attributes, and properties you choose to allow. Using a simple configuration syntax, you can tell Sanitize to allow certain HTML elements, certain attributes within those elements, and even certain URL protocols within attributes that contain URLs. You can also allow specific CSS properties, @ rules, and URL protocols in elements or attributes containing CSS. Any HTML or CSS that you don't explicitly allow will be removed. Sanitize is based on the [Nokogiri HTML5 parser][nokogiri], which parses HTML the same way modern browsers do, and [Crass][crass], which parses CSS the same way modern browsers do. [![Gem Version](https://badge.fury.io/rb/sanitize.svg)](http://badge.fury.io/rb/sanitize) [![Tests](https://github.com/rgrove/sanitize/workflows/Tests/badge.svg)](https://github.com/rgrove/sanitize/actions?query=workflow%3ATests) [crass]:https://github.com/rgrove/crass [nokogiri]:https://github.com/sparklemotion/nokogiri > [!WARNING] > > Sanitize cannot fully sanitize the contents of `` or `` elements. MathML and SVG elements are [foreign elements](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements) that don't follow normal HTML parsing rules. > > By default, Sanitize will remove all MathML and SVG elements. If you add MathML or SVG elements to a custom element allowlist, you may create a security vulnerability in your application. ## Links * [Home](https://github.com/rgrove/sanitize/) * [API Docs](https://rubydoc.info/gems/sanitize/Sanitize) * [Issues](https://github.com/rgrove/sanitize/issues) * [Release History](https://github.com/rgrove/sanitize/releases) * [Online Demo](https://sanitize-web.fly.dev/) ## Installation ``` gem install sanitize ``` ## Quick Start ```ruby require 'sanitize' # Clean up an HTML fragment using Sanitize's permissive but safe Relaxed config. # This also sanitizes any CSS in `foo' Sanitize.fragment(html) # => "foo" ``` To keep certain elements, add them to the element allowlist. ```ruby Sanitize.fragment(html, elements: ['b']) # => "foo" ``` ### HTML Documents When sanitizing a document, the `` element must be allowlisted. You can also set `:allow_doctype` to `true` to allow well-formed document type definitions. ```ruby html = %[ foo ] Sanitize.document(html, allow_doctype: true, elements: ['html'] ) # => "foo\n \n" ``` ### CSS in HTML To sanitize CSS in an HTML fragment or document, first allowlist the `

hello!

] Sanitize.fragment(html, elements: ['div', 'style'], attributes: {'div' => ['style']}, css: { properties: ['width'] } ) #=> %[ # # #
# hello! # ] ``` ### Standalone CSS Sanitize will happily clean up a standalone CSS stylesheet or property string without needing to invoke the HTML parser. > [!WARNING] > This should only be used to sanitize CSS for use in a standalone CSS file. To safely sanitize CSS for use in an HTML context, such as in a `