i'm wondering how safe it is to use createHTMLDocument
to do HTML sanitization. I've tried to implement it like this:
function sanitize(string) {
var elm = document.implementation.createHTMLDocument().body;
elm.innerHTML = string;
// traverse and filter elm to only allow whitelisted elements and attributes
// e.g. use https://github.com/gbirke/Sanitize.js
var cleaned_fragment = whitelist_filter(elm);
elm = document.implementation.createHTMLDocument().body;
elm.appendChild(cleaned_fragment);
return elm.innerHTML;
}
It seems to work fine with all XSS attacks i've throw at it (no script evaluation or requests triggered). But I got a feeling it might be a bad idea, im I missing something?
I've created a jsfiddle if someone wants to experiment.
DOMParser
,createHTMLDocument
ortoStaticHTML