class Rails::Html::WhiteListSanitizer
white_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)
White list via a custom scrubber
attributes: %w(id class style))
white_list_sanitizer.sanitize(@article.body, tags: %w(table tr td),
White list via the supplied tags and attributes
white_list_sanitizer.sanitize(@article.body)
Default: sanitize via a extensive white list of allowed elements
white_list_sanitizer.sanitize_css(‘background-color: #000;’)
Sanitize css doesn’t take options
white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
=== Examples
Passed options take precedence over the class level options.
Tags and attributes can also be passed to sanitize
.
Rails::Html::WhiteListSanitizer.allowed_attributes = %w(id class style)
Rails::Html::WhiteListSanitizer.allowed_tags = %w(table tr td)
There’s a class level option:
the white list used when sanitizing html.
WhiteListSanitizer also accepts options to configure
Sanitizes both html and css via the white lists found here:
=== Options
so automatically.
wrap their whitespace sensitive content in pre tags or that you do
whitespace into account anyway. It might be better to suggest your users
When the stripped markup will be rendered the users browser won’t take
Those two parsers determine how whitespace is ultimately handled.
respective Ruby implementation.
Loofah uses Nokogiri, which wraps either a C or Java parser for the
We can’t make any guarentees about whitespace being kept or stripped.
=== Whitespace
Sanitizes html and css from an extensive white list (see link further down).
=== Rails::Html::WhiteListSanitizer
def allowed_attributes(options)
def allowed_attributes(options) options[:attributes] || self.class.allowed_attributes end
def allowed_tags(options)
def allowed_tags(options) options[:tags] || self.class.allowed_tags end
def initialize
def initialize @permit_scrubber = PermitScrubber.new end
def sanitize(html, options = {})
def sanitize(html, options = {}) return unless html return html if html.empty? loofah_fragment = Loofah.fragment(html) if scrubber = options[:scrubber] # No duck typing, Loofah ensures subclass of Loofah::Scrubber loofah_fragment.scrub!(scrubber) elsif allowed_tags(options) || allowed_attributes(options) @permit_scrubber.tags = allowed_tags(options) @permit_scrubber.attributes = allowed_attributes(options) loofah_fragment.scrub!(@permit_scrubber) else remove_xpaths(loofah_fragment, XPATHS_TO_REMOVE) loofah_fragment.scrub!(:strip) end properly_encode(loofah_fragment, encoding: 'UTF-8') end
def sanitize_css(style_string)
def sanitize_css(style_string) Loofah::HTML5::Scrub.scrub_css(style_string) end