Element: setHTML() method

What setHTML() Is and Why It Exists

  • Seen as a “safe innerHTML” or built‑in DOMPurify: a standardized way to sanitize and insert untrusted HTML into the DOM.
  • Main use case: rendering user-generated content (social media, CMS, search results, etc.) without letting users sneak in scripts or event handlers (XSS).
  • Several commenters emphasize that getting HTML sanitization right is hard, and a platform primitive is overdue after decades of XSS issues.

Security Model and HTTPS Confusion

  • Some confusion about HTTPS vs XSS: others clarify that TLS only secures transport; XSS is about attacker-controlled HTML/JS executing in the browser and is unrelated to HTTPS.
  • setHTML is aimed at preventing XSS in the browser, not securing the network channel.

Client vs Server Sanitization

  • Strong disagreement here:
    • One side: you must always sanitize on the server to protect the backend and storage; never trust the client; double-escaping is acceptable.
    • Other side: you should store raw user input and sanitize/escape as close as possible to each use (HTML, SMS, logs, SQL, native app) because each medium has different rules.
  • Clarifications:
    • “Sanitizing” for HTML is distinct from transport-level safety and from things like SQL injection, which are better handled via parameterized queries.
    • The consumer of data (e.g., browser, native client) is generally responsible for context-appropriate sanitization.

API Design, Naming, and Behavior

  • Some praise the ergonomic choice: setHTML() is safe by default; the unsafe path (setHTMLUnsafe / innerHTML) is more explicit and scary.
  • Others dislike the name: they expected “plain set HTML” semantics, not non‑overrideable XSS filtering; suggestions include safeSetHTML or sanitizeAndSetHTML.
  • Debate over the fact that scripts are stripped even if explicitly allowed in the sanitizer config; defenders argue that running script here is almost always a footgun, and unsafe behavior should remain harder to reach.

Frameworks, Libraries, and Polyfills

  • Framework authors are interested in using setHTML() to implement “safeHTML” directives; today they rely on optional libraries like DOMPurify, which are relatively large.
  • Some argue this could stay a library feature; others counter that a spec’d, built-in sanitizer ensures consistency and performance.
  • There’s a polyfill that wraps DOMPurify so developers can adopt the API before broad browser support.

“Don’t Roll Your Own” Sanitizer

  • Multiple comments warn against homegrown or regex-based sanitizers; HTML is complex, and real-world bypasses are non-trivial.
  • An AI-generated “pseudo-sethtml” using regex is shown to be trivially bypassable, used as an example of why serious, maintained libraries or the standardized API are needed.