DOMPurify
v3.4.17Fast, tolerant XSS sanitiser for HTML, MathML and SVG.
Quick start
Add this tag to your page. Place it just before the closing </body> tag, or in the <head> with the defer attribute.
HTML
<script src="https://jscdns.net/libs/dompurify/3.4.17/purify.min.js"
integrity="sha384-P0JNneQf81HOl9VwNXK76cQ9VMD6Nfsnepxb0cCOg8+UzEdzgPHAPV4wVQrvYQSx" crossorigin="anonymous"></script>Files
| File | Size | Copy |
|---|---|---|
| purify.min.jsScript | 29.1 KB |
Usage
Complete example
A minimal page that loads DOMPurify and uses it. Copy it into a file and open it in your browser.
example.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="comment"></div>
<script src="https://jscdns.net/libs/dompurify/3.4.17/purify.min.js"
integrity="sha384-P0JNneQf81HOl9VwNXK76cQ9VMD6Nfsnepxb0cCOg8+UzEdzgPHAPV4wVQrvYQSx" crossorigin="anonymous"></script>
<script>
const untrusted = '<img src=x onerror="alert(1)"><b>Hello</b>';
document.querySelector('#comment').innerHTML = DOMPurify.sanitize(untrusted);
// Result: <img src="x"><b>Hello</b>
</script>
</body>
</html>Good to know. Always sanitise untrusted HTML before inserting it with innerHTML. DOMPurify pairs well with Marked when rendering user supplied Markdown.