HtmlSanitizeEx (html_sanitize_ex v1.5.1)

Copy Markdown View Source

HtmlSanitizeEx can be used to sanitize potentially malicious user input.

It provides four convenience functions:

These functions are shortcuts to the respective "scrubber", a module that does the sanitization.

Create custom scrubbers

HtmlSanitizeEx can be used to implement custom scrubbers:

defmodule MyMostBasicScrubber do
  use HtmlSanitizeEx

  allow_tag_with_these_attributes("p", ["class"])
end

This creates a scrubber that only allows p tags, optionally with a class attribute.

iex(1)> MyMostBasicScrubber.sanitize(
...(2)>   "<p class=\"success\" title=\"Success!\"><strong>Granted</strong> access!</p>")
"<p class=\"success\">Granted access!</p>"

Extend existing scrubbers

Implementing scrubbers from scratch can be daunting, which is why HtmlSanitizeEx also supports extending existing scrubbers:

defmodule MyScrubber do
  use HtmlSanitizeEx, extend: :basic_html

  allow_tag_with_any_attributes("p")
end

This creates a scrubber working exactly like HtmlSanitizeEx.basic_html/1, but allows p tags with any attribute.

You can extend :basic_html, :html5, :markdown_html and :strip_tags.

You can also extend any custom scrubber you created:

defmodule FooBarScrubber do
  use HtmlSanitizeEx, extend: MyMostBasicScrubber

  allow_tag_with_these_attributes("p", ["title"])
end

This creates a scrubber that only allows p tags, optionally with class and title attributes.

iex(1)> FooBarScrubber.sanitize(
...(2)>   "<p class=\"success\" title=\"Success!\"><strong>Granted</strong> access!</p>")
"<p class=\"success\" title=\"Success!\">Granted access!</p>"

Summary

Functions

Allows basic HTML tags to support user input for writing relatively plain text but allowing headings, links, bold, and so on.

Allows all HTML5 tags to support user input.

Allows basic HTML tags to support user input for writing relatively plain text with Markdown (GitHub flavoured Markdown supported).

Scrubs neither tags, nor their attributes.

Strips all tags (and, naturally, attributes).

Functions

basic_html(html)

Allows basic HTML tags to support user input for writing relatively plain text but allowing headings, links, bold, and so on.

Does not allow any styling, HTML5 tags, video embeds etc.

html5(html)

Allows all HTML5 tags to support user input.

Sanitizes all malicious content.

markdown_html(html)

Allows basic HTML tags to support user input for writing relatively plain text with Markdown (GitHub flavoured Markdown supported).

Technically this is a more relaxed version of the BasicHTML scrubber.

Does not allow any styling, HTML5 tags, video embeds etc.

noscrub(html)

Scrubs neither tags, nor their attributes.

strip_tags(html)

Strips all tags (and, naturally, attributes).