Skip to content
Jonathan edited this page Jun 16, 2022 · 5 revisions

HtmlSanitizer provides the following events.

  • PostProcessNode (PostProcessNodeEventArgs)
  • RemovingTag (RemovingTagEventArgs)
  • RemovingAttribute (RemovingAttributeEventArgs)
  • RemovingStyle (RemovingStyleEventArgs)
  • RemovingAtRule (RemovingAtRuleEventArgs)
  • RemovingComment (RemovingCommentEventArgs)
  • RemovingCssClass (RemovingCssClassEventArgs)
  • FilterUrl (FilterUrlEventArgs)

Each of these events can be subscribed to using either delegate methods or lambda expressions, like so:

var sanitizer = new HtmlSanitizer();
sanitizer.RemovingTag += (sender, e) => e.Cancel = e.Tag.NodeName == "BLINK";

Each of the Removing... events can be cancelled, as their event object derives from System.ComponentModel.CancelEventArgs. sender, in the above example, is the instance of HtmlSanitizer which raised this event, e, in the above example.

You can also use these events to override the default behavior. For instance, let's assume you want to throw an exception if a specific tag is present in the input string:

var sanitizer = new HtmlSanitizer();
sanitizer.RemovingTag += (sender, e) => 
{
    if (e.Tag.NodeName.Equals("BLINK", StringComparison.OrdinalIgnoreCase))
    {
        throw new ItsNot1999Exception("blink");
    }
}
Clone this wiki locally