I'm using DomPurify to sanitize SVG code.
It works fine however I would like to show a message if SVG code entered in a textarea is not valid.
I'm trying to compare the SVG code added with the SVG code sanitized. If they are different I will show a message.
function validate() {
if( svgCode.trim() === DOMPurify.sanitize(svgCode).trim() ) {
console.log('All right!');
} else {
console.log('Uuuh-oooh! The SVG code is not valid!');
}
}
validate();
The issue: I keep getting Uuuh-oooh! The SVG code is not valid! because dompurify turns closing paths like /> into full paths '`.
You can use removed property to check if any sanitization happened or not.
e.g.
DOMPurify.sanitize('<svg onload=alert(1) />');
console.log(DOMPurify.removed.length); // 1
DOMPurify.sanitize('<svg />');
console.log(DOMPurify.removed.length); // 0
https://github.com/is2ei/DOMPurify#okay-makes-sense-lets-move-on
After sanitizing your markup, you can also have a look at the property DOMPurify.removed and find out, what elements and attributes were thrown out. Please do not use this property for making any security critical decisions. This is just a little helper for curious minds.