Class: Rails::HTML5::SafeListSanitizer

Overview

Rails::HTML5::SafeListSanitizer

Sanitizes HTML5 and CSS from an extensive safe list.

Whitespace

We can’t make any guarantees about whitespace being kept or stripped. Loofah uses Nokogiri, which wraps either a C or Java parser for the respective Ruby implementation. Those two parsers determine how whitespace is ultimately handled.

When the stripped markup will be rendered the users browser won’t take whitespace into account anyway. It might be better to suggest your users wrap their whitespace sensitive content in pre tags or that you do so automatically.

Options

Sanitizes both html and css via the safe lists found in Rails::HTML::Concern::Scrubber::SafeList

SafeListSanitizer also accepts options to configure the safe list used when sanitizing html. There’s a class level option:

Rails::HTML5::SafeListSanitizer.allowed_tags = %w(table tr td)
Rails::HTML5::SafeListSanitizer.allowed_attributes = %w(id class style)

Tags and attributes can also be passed to sanitize. Passed options take precedence over the class level options.

Examples

safe_list_sanitizer = Rails::HTML5::SafeListSanitizer.new

# default: sanitize via a extensive safe list of allowed elements
safe_list_sanitizer.sanitize(@article.body)

# sanitize via the supplied tags and attributes
safe_list_sanitizer.sanitize(
  @article.body,
  tags: %w(table tr td),
  attributes: %w(id class style),
)

# sanitize via a custom Loofah scrubber
safe_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)

# prune nodes from the tree instead of stripping tags and leaving inner content
safe_list_sanitizer = Rails::HTML5::SafeListSanitizer.new(prune: true)

# the sanitizer can also sanitize CSS
safe_list_sanitizer.sanitize_css('background-color: #000;')

Constant Summary

Constants included from Rails::HTML::Concern::Scrubber::SafeList

Rails::HTML::Concern::Scrubber::SafeList::DEFAULT_ALLOWED_ATTRIBUTES, Rails::HTML::Concern::Scrubber::SafeList::DEFAULT_ALLOWED_TAGS

Constants inherited from Rails::HTML::Sanitizer

Rails::HTML::Sanitizer::VERSION

Method Summary

Methods included from Rails::HTML::Concern::Serializer::UTF8Encode

#serialize

Methods included from Rails::HTML::Concern::Scrubber::SafeList

included, #initialize, #sanitize_css, #scrub

Methods included from Rails::HTML::Concern::Parser::HTML5

#parse_fragment

Methods included from Rails::HTML::Concern::ComposedSanitize

#sanitize

Methods inherited from Rails::HTML::Sanitizer

best_supported_vendor, html5_support?, #sanitize

Methods included from Rails::HTML4::Sanitizer::VendorMethods

#full_sanitizer, #link_sanitizer, #safe_list_sanitizer, #white_list_sanitizer