/ shared / components / src / utils / sanitize-html / browser.ts
browser.ts
 1  // Browser ONLY logic. Must have the same exports as server.ts
 2  // See: docs/isomorphic-imports.md
 3  
 4  import { type SanitizeHtmlOptions, sanitizeDocument } from './common';
 5  
 6  export { type SanitizeHtmlOptions, DEFAULT_SAFE_TAGS } from './common';
 7  
 8  // Shared DOMParser instance (avoids creating a new one for each sanitization)
 9  let parser = null;
10  
11  export function sanitizeHtml(
12      input: string,
13      options: SanitizeHtmlOptions = {},
14  ): string {
15      if (!input) {
16          return input;
17      }
18  
19      if (!parser) {
20          parser = new DOMParser();
21      }
22  
23      const unsafeDocument = parser.parseFromString(`${input}`, 'text/html');
24      const unsafeNode = unsafeDocument.body;
25      return sanitizeDocument(unsafeDocument, unsafeNode, options);
26  }