dompurify
Version:
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Firefox and Chrome - as well as almost anything else usin
50 lines (45 loc) • 2.08 kB
HTML
<html>
<head>
<script src="../src/purify.js"></script>
</head>
<body>
<!-- Our DIV to receive content -->
<div id="sanitized"></div>
<!-- Now let's sanitize that content -->
<script>
/* jshint globalstrict:true */
/* global DOMPurify */
'use strict';
// Specify dirty HTML
var dirty = '<a href="?a">CLICK</a>\
<a href="?a" target="jajaja">CLICK</a>\
<svg><a href="?svg"><circle r=40></a></svg>\
<form action="?form"><input type="submit"></form>\
<img src="404" width="200" height="200" usemap="#test">\
<map name="test"><area href="?area" shape="rect" \
coords="0,0,200,200"></area></map>\
<math href="?mathml">CLICKME</math>\
<math><mi href="?mathml">CLICKME</mi></math>\
<math><mi target="xxx" href="?mathml">CLICKME</mi></math>\
<svg xmlns:xlink="http://www.w3.org/2000/svg"><a xlink:href="?bla"><circle r=40></a></svg>\
';
// Add a hook to make all links open a new window
DOMPurify.addHook('afterSanitizeAttributes', function(node) {
// set all elements owning target to target=_blank
if ('target' in node) {
node.setAttribute('target','_blank');
}
// set non-HTML/MathML links to xlink:show=new
if (!node.hasAttribute('target')
&& (node.hasAttribute('xlink:href')
|| node.hasAttribute('href'))) {
node.setAttribute('xlink:show', 'new');
}
});
// Clean HTML string and write into our DIV
var clean = DOMPurify.sanitize(dirty);
document.getElementById('sanitized').innerHTML = clean;
</script>
</body>
</html>