| 1 |
<!doctype html> |
| 2 |
<html lang="en"> |
| 3 |
<head> |
| 4 |
<meta charset="utf-8" /> |
| 5 |
<title>DOMPurify demo: Sanitize SVGs shown via an img tag</title> |
| 6 |
<script src="../dist/purify.js"></script> |
| 7 |
</head> |
| 8 |
<body> |
| 9 |
|
| 10 |
<div id="sanitized"></div> |
| 11 |
|
| 12 |
|
| 13 |
<script> |
| 14 |
'use strict'; |
| 15 |
|
| 16 |
// An SVG as exported by Adobe Illustrator, including the |
| 17 |
// namespace declarations DOMPurify strips by default and a |
| 18 |
// <filter> element, which is not allowed by default. |
| 19 |
const dirty = `<?xml version="1.0" encoding="utf-8"?> |
| 20 |
<!-- Generator: Adobe Illustrator --> |
| 21 |
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" |
| 22 |
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100"> |
| 23 |
<filter id="blur"><feGaussianBlur stdDeviation="2"/></filter> |
| 24 |
<circle cx="50" cy="50" r="40" fill="teal" filter="url(#blur)" |
| 25 |
onclick="alert(document.domain)"/> |
| 26 |
</svg>`; |
| 27 |
|
| 28 |
// Add a hook to post-process the sanitized SVG root: re-add the |
| 29 |
// namespaces (added by tools like Illustrator, stripped during |
| 30 |
// sanitization) that an <img>-embedded SVG needs to render. |
| 31 |
DOMPurify.addHook('afterSanitizeAttributes', function (node) { |
| 32 |
if (node.tagName && node.tagName.toLowerCase() === 'svg') { |
| 33 |
node.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); |
| 34 |
node.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); |
| 35 |
} |
| 36 |
}); |
| 37 |
|
| 38 |
// Clean the SVG string and allow the "filter" tag |
| 39 |
const clean = DOMPurify.sanitize(dirty, { ADD_TAGS: ['filter'] }); |
| 40 |
|
| 41 |
// Show the sanitized content in an <img> element |
| 42 |
const img = new Image(); |
| 43 |
img.src = 'data:image/svg+xml;base64,' + window.btoa(clean); |
| 44 |
document.getElementById('sanitized').appendChild(img); |
| 45 |
</script> |
| 46 |
</body> |
| 47 |
</html> |