sanitizeHtml function

String sanitizeHtml(
  1. String html
)

Strips the most common XSS vectors from raw HTML: <script> elements and inline event-handler attributes (on*). This is a baseline defence, not a full HTML sanitizer - pass it as UnsafeHtmlNode.sanitizer when the raw HTML cannot be fully trusted.

Implementation

String sanitizeHtml(String html) {
  var clean = html;
  clean = clean.replaceAll(
    RegExp(r'<script[^>]*>[\s\S]*?</script>', caseSensitive: false),
    '',
  );
  clean = clean.replaceAll(
    RegExp(r'\s+on\w+\s*=\s*"[^"]*"', caseSensitive: false),
    '',
  );
  clean = clean.replaceAll(
    RegExp(r"\s+on\w+\s*=\s*'[^']*'", caseSensitive: false),
    '',
  );
  return clean;
}