Skip to content

Commit

Permalink
Create customizable comment encoding method (fixes #525)
Browse files Browse the repository at this point in the history
  • Loading branch information
mganss committed Feb 1, 2024
1 parent 8a62437 commit 9254a13
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/HtmlSanitizer/HtmlSanitizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ public HtmlSanitizer(HtmlSanitizerOptions options)
AllowedAtRules = new HashSet<CssRuleType>(options.AllowedAtRules);
}

/// <summary>
/// Gets or sets the default <see cref="Action{IComment}"/> method that encodes comments.
/// </summary>
public Action<IComment> EncodeComment { get; set; } = DefaultEncodeComment;

/// <summary>
/// Gets or sets the default <see cref="Action{IElement}"/> method that encodes literal text content.
/// </summary>
Expand Down Expand Up @@ -458,9 +463,7 @@ private void RemoveComments(INode context)
{
foreach (var comment in GetAllNodes(context).OfType<IComment>().ToList())
{
var escapedText = comment.TextContent.Replace("<", "&lt;").Replace(">", "&gt;");
if (escapedText != comment.TextContent)
comment.TextContent = escapedText;
EncodeComment(comment);

var e = new RemovingCommentEventArgs(comment);
OnRemovingComment(e);
Expand All @@ -470,6 +473,13 @@ private void RemoveComments(INode context)
}
}

private static void DefaultEncodeComment(IComment comment)
{
var escapedText = comment.TextContent.Replace("<", "&lt;").Replace(">", "&gt;");
if (escapedText != comment.TextContent)
comment.TextContent = escapedText;
}

private static void DefaultEncodeLiteralTextElementContent(IElement tag)
{
var escapedHtml = tag.InnerHtml.Replace("<", "&lt;").Replace(">", "&gt;");
Expand Down

0 comments on commit 9254a13

Please sign in to comment.