HtmlSanitizeEx can be used to sanitize potentially malicious user input.
It provides four convenience functions:
HtmlSanitizeEx.strip_tags/1- to simply strip all HTML tagsHtmlSanitizeEx.basic_html/1- to allow for basic HTMLHtmlSanitizeEx.markdown_html/1- to allow for a subset of HTML that is ouput by Markdown parsersHtmlSanitizeEx.html5/1- to allow full HTML5 while scrubbing malicious elements
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"])
endThis 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")
endThis 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"])
endThis 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
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.
Allows all HTML5 tags to support user input.
Sanitizes all malicious content.
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.
Scrubs neither tags, nor their attributes.
Strips all tags (and, naturally, attributes).