Element: setHTML() method
6 months ago
- #javascript
- #web-development
- #security
- The `setHTML()` method of the `Element` interface provides an XSS-safe way to parse and sanitize HTML strings into a `DocumentFragment` before inserting them into the DOM.
- It requires an `input` string of HTML and an optional `options` object that can specify a `Sanitizer` or `SanitizerConfig` to control allowed or removed elements.
- The method automatically removes XSS-unsafe elements and attributes, even if they are allowed by the sanitizer configuration.
- `setHTML()` should be used over `innerHTML` or `setHTMLUnsafe()` for inserting untrusted HTML to prevent XSS attacks.
- Examples demonstrate using default and custom sanitizers, showing how unsafe elements like `<script>` are always removed regardless of sanitizer settings.
- The method is experimental and not widely supported, so browser compatibility should be checked before use in production.