API Reference

This page lists Loofah's public API: module methods, the document classes' added methods, Loofah::Scrubber, the built-in scrubbers, the sanitization functions, constants, and exceptions. Each entry gives the signature, parameters, return value, errors, and a short example. Methods inherited from Nokogiri are not repeated here.

Feature Detection

Loofah.html5_support?

Loofah.html5_support? # => true or false

Returns true when Nokogiri is newer than 1.14.0 and was built with the Gumbo HTML5 parser. The result is memoized. When false, the Loofah::HTML5::Document and Loofah::HTML5::DocumentFragment constants are undefined and the html5_* methods raise NotImplementedError. See Installation.

Parsing and Scrubbing Shorthands

Method Equivalent to Returns
Loofah.html5_document(*args, &block) Loofah::HTML5::Document.parse(*args, &block) Loofah::HTML5::Document
Loofah.html5_fragment(tags, encoding = nil) Loofah::HTML5::DocumentFragment.parse(...) Loofah::HTML5::DocumentFragment
Loofah.scrub_html5_document(string_or_io, method) Loofah::HTML5::Document.parse(string_or_io).scrub!(method) Loofah::HTML5::Document
Loofah.scrub_html5_fragment(string_or_io, method) Loofah::HTML5::DocumentFragment.parse(string_or_io).scrub!(method) Loofah::HTML5::DocumentFragment
Loofah.html4_document(*args, &block) Loofah::HTML4::Document.parse(*args, &block) Loofah::HTML4::Document
Loofah.html4_fragment(tags, encoding = nil) Loofah::HTML4::DocumentFragment.parse(...) Loofah::HTML4::DocumentFragment
Loofah.scrub_html4_document(string_or_io, method) Loofah::HTML4::Document.parse(string_or_io).scrub!(method) Loofah::HTML4::Document
Loofah.scrub_html4_fragment(string_or_io, method) Loofah::HTML4::DocumentFragment.parse(string_or_io).scrub!(method) Loofah::HTML4::DocumentFragment
Loofah.xml_document(*args, &block) Loofah::XML::Document.parse(*args, &block) Loofah::XML::Document
Loofah.xml_fragment(tags) Loofah::XML::DocumentFragment.parse(tags) Loofah::XML::DocumentFragment
Loofah.scrub_xml_document(string_or_io, method) Loofah.xml_document(string_or_io).scrub!(method) Loofah::XML::Document
Loofah.scrub_xml_fragment(string_or_io, method) Loofah.xml_fragment(string_or_io).scrub!(method) Loofah::XML::DocumentFragment
Loofah.document alias of html4_document
Loofah.fragment alias of html4_fragment
Loofah.scrub_document alias of scrub_html4_document
Loofah.scrub_fragment alias of scrub_html4_fragment

Parameters:

Parameter Type Description
string_or_io, tags String or IO Markup, or any object responding to read and close
method Symbol or Loofah::Scrubber A built-in scrubber name (see Loofah::Scrubbers::MAP) or a scrubber instance
encoding String or nil Encoding name for HTML fragments; defaults to the input string's encoding, else "UTF-8"
*args Forwarded to Nokogiri's document parse (for example URL, encoding, options)

Errors: the html5_* methods raise NotImplementedError (Loofah::HTML5 is not supported by your version of Nokogiri) without HTML5 support. The scrub_* methods raise Loofah::ScrubberNotFound for an unknown method. Fragment methods raise ArgumentError if given more arguments than listed.

Loofah.scrub_html5_fragment("<b>ok</b><script>no</script>", :prune).to_s
# => "<b>ok</b>"

Note: The aliases document, fragment, scrub_document, and scrub_fragment use the HTML4 parser today and may switch to HTML5 in a future version. Call the explicit html4_* or html5_* methods instead.

Utility Methods

Loofah.remove_extraneous_whitespace(string)

Replaces every match of /\n\s*\n\s*\n/ with "\n\n" and returns the new string. Since \s also matches newlines, any run of three or more newlines (with spaces or tabs mixed in) collapses to exactly one blank line. Used by to_text.

Loofah.remove_extraneous_whitespace("a\n\n\n\nb")      # => "a\n\nb"
Loofah.remove_extraneous_whitespace("a\n\n\t\n \nb")   # => "a\n\nb"

ScrubBehavior: scrub!

#scrub!(scrubber)

Available on Loofah HTML and XML documents and fragments, and on every Nokogiri::XML::Node and NodeSet obtained from them.

Parameter Type Description
scrubber Symbol or Loofah::Scrubber Built-in name or scrubber instance

Returns the receiver, modified in place. Raises Loofah::ScrubberNotFound with not a Scrubber or a scrubber name: <inspect> if the argument is neither.

Receiver Traverses
Document root and its subtree, or nothing if there is no root
Fragment Each child
Node The node and its subtree
NodeSet Each node in the set
doc = Loofah.html5_document(html)
doc.css(".comment").scrub!(:prune)

TextBehavior Methods

Available on Loofah::HTML5::Document, Loofah::HTML5::DocumentFragment, Loofah::HTML4::Document, and Loofah::HTML4::DocumentFragment.

#text(options = {})

Returns the text content of the body (documents) or top-level nodes (fragments), excluding top-level comments.

Option Default Effect
:encode_special_chars true (any value other than false) Escape <, >, & in the result

Aliases: inner_text, to_str.

Loofah.html5_document("<h1>Title</h1><div>Content</div>").text # => "TitleContent"

#to_text(options = {})

Returns plain text with newlines around block-level elements and in place of <br>, then collapses extra blank lines. Takes the same options as text. Does not modify the receiver.

Loofah.html5_document("<h1>Title</h1><div>Content<br>Next line</div>").to_text
# => "\nTitle\n\nContent\nNext line\n"

Fragment #to_s / #serialize

On HTML fragments, returns the HTML of the fragment's content without wrapper elements. See Text Output.

Loofah::Scrubber

Loofah::Scrubber.new(options = {}, &block)

Parameter Description
options[:direction] :top_down (default) or :bottom_up
block Called with each node. If omitted, the instance's scrub(node) method is called instead

Raises ArgumentError (direction <value> must be one of :top_down or :bottom_up) for any other direction.

Instance methods

Method Description
direction The traversal direction (reader)
block The block given to new, or nil (reader)
traverse(node) Walk node's subtree in the configured direction, calling the block or scrub
scrub(node) Override in subclasses. The default raises Loofah::ScrubberNotFound (No scrub method has been defined on <Class>)
append_attribute(node, attribute, value) Add value to a whitespace-separated attribute if not already present; creates the attribute if missing

Constants

Constant Meaning
Loofah::Scrubber::STOP Returned from a top-down scrubber: skip this node's children
Loofah::Scrubber::CONTINUE Returned from a top-down scrubber: visit this node's children (the default for any other return value)

See Custom Scrubbers for usage.

Loofah::Scrubbers

Loofah::Scrubbers::MAP

A hash from symbol to scrubber class, used by scrub!:

Symbol Class Direction Page
:escape Loofah::Scrubbers::Escape top-down Sanitizing
:prune Loofah::Scrubbers::Prune top-down Sanitizing
:whitewash Loofah::Scrubbers::Whitewash top-down Sanitizing
:strip Loofah::Scrubbers::Strip bottom-up Sanitizing
:nofollow Loofah::Scrubbers::NoFollow top-down Links and text
:noopener Loofah::Scrubbers::NoOpener top-down Links and text
:noreferrer Loofah::Scrubbers::NoReferrer top-down Links and text
:targetblank Loofah::Scrubbers::TargetBlank top-down Links and text
:newline_block_elements Loofah::Scrubbers::NewlineBlockElements bottom-up Links and text
:unprintable Loofah::Scrubbers::Unprintable top-down Links and text
:double_breakpoint Loofah::Scrubbers::DoubleBreakpoint bottom-up Links and text

The classes can also be instantiated directly (Loofah::Scrubbers::Prune.new) and passed to scrub!. Their initialize takes no arguments.

Loofah::Scrubbers.scrubber_symbols

Returns MAP.keys, the array of built-in scrubber names:

Loofah::Scrubbers.scrubber_symbols
# => [:escape, :prune, :whitewash, :strip, :nofollow, :noopener, :noreferrer,
#     :targetblank, :newline_block_elements, :unprintable, :double_breakpoint]

Loofah::HTML5::Scrub

Module functions used by the sanitizers. Although the enclosing module is marked :nodoc:, allowed_uri? is documented in its source as usable without a DOM node, and scrub_css is the implementation behind Loofah::Helpers.sanitize_css.

Method Returns Description
allowed_element?(name) Boolean Is name in SafeList::ALLOWED_ELEMENTS_WITH_LIBXML2?
scrub_attributes(node) Clean all attributes of an element node in place (details)
scrub_css_attribute(node) Run scrub_css on the node's style attribute, if any
scrub_css(style) String Sanitized CSS declarations (details)
allowed_uri?(uri_string) Boolean Is the URI safe? (details)
scrub_uri_attribute(attr_node) Boolean Remove the attribute if its value fails allowed_uri?; returns true if removed
scrub_attribute_that_allows_local_ref(attr_node) Keep only local url(#...) references and plain tokens
decode_numeric_character_references(string) String Decode &#NN / &#xHH references, with or without ;
force_correct_attribute_escaping!(node) libxml2 workaround (details)
cdata_needs_escaping?(node) Boolean Is this CDATA (or JRuby <style> text) that must be escaped?
cdata_escape(node) Node New CDATA or text node with <, >, & escaped
escape_tags(string) String Escape <, >, &, preserving the string's encoding
Loofah::HTML5::Scrub.escape_tags("<b>a & b</b>") # => "&lt;b&gt;a &amp; b&lt;/b&gt;"

Loofah::Elements

Set constants of element names, with lower-cased copies of every entry:

Constant Contents
STRICT_BLOCK_LEVEL_HTML4 HTML4 block-level elements
STRICT_BLOCK_LEVEL_HTML5 HTML5 block-level elements (from MDN's list)
LOOSE_BLOCK_LEVEL Elements that may contain block-level elements (dd, dt, frameset, li, tbody, td, tfoot, th, thead, tr)
INLINE_LINE_BREAK br
STRICT_BLOCK_LEVEL STRICT_BLOCK_LEVEL_HTML4 + STRICT_BLOCK_LEVEL_HTML5
BLOCK_LEVEL STRICT_BLOCK_LEVEL + LOOSE_BLOCK_LEVEL
LINEBREAKERS BLOCK_LEVEL + INLINE_LINE_BREAK

The full lists are on the Text Output page.

Constants and Aliases

Name Description
Loofah::VERSION Gem version string, "2.25.2" in the current source
Loofah::HTML Alias of Loofah::HTML4
Loofah::HTML5::SafeList Safelist constants (reference)
Loofah::HTML5::WhiteList Deprecated alias of SafeList
Loofah::LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES href, action, src, name
Loofah::LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES_QUALIFYING_TAG { "name" => "a" }
Loofah::HTML5::Scrub::CONTROL_CHARACTERS Characters stripped from URIs before checking
Loofah::HTML5::Scrub::DATA_ATTRIBUTE_NAME /\Adata-[\w-]+\z/, the always-allowed attribute pattern
Loofah::HTML5::Scrub::URI_PROTOCOL_REGEX Matches a scheme followed by a protocol separator

Exceptions

Exception Superclass Raised when
Loofah::ScrubberNotFound RuntimeError scrub! gets an unknown name or a non-scrubber; a scrubber has neither block nor scrub
ArgumentError Invalid :direction; extra arguments to fragment parse; HTML fragment class with an unexpected subclass
NotImplementedError html5_* methods without HTML5 support

For the helpers in loofah/helpers, see Rails Helpers.

See Also