Allow HTML comments in DomPurify

2.5k views Asked by At

I would like to use DOMPurify to sanitise some HTML content, but I'd like to preserve the HTML comments. Is that possible?

You can see what it does in this example - if you enter markup with a comment the comment is stripped out.

DOMPurify seems very configurable, but the docs don't mention what term to use to specify HTML comment as an allowed tag.

2

There are 2 answers

0
front_end_dev On BEST ANSWER

DOMPurify doesn't have any hooks or configuration to allow comments in html string. You can do one this just replace the <!-- and --> to any custom attribute and provide configuration to allow ADD_TAGS: ['comment'] it.

var dirty = "<!-- I am ready now, click one of the buttons! -->ac <script>in script<\/script> <b>hello</b>";
dirty = dirty.replace(/(<!--)/g,'<comment>').replace(/(-->)/g,'</comment>');
var config = { ALLOWED_TAGS: ['b'],ADD_TAGS: ['comment']};
var clean = DOMPurify.sanitize(dirty, config);
clean = clean.replace(/(<comment>)/g,'<!--').replace(/(<\/comment>)/g,'-->');
console.log("clean => ",clean);

jsFiddle demo - http://jsfiddle.net/4j6c28ve/

1
Lasse On

I had the same question, there's a much better solution for this, that is not messing around with regex in markup (spoiler alert: don't!):

var dirty = "<!-- I am ready now, click one of the buttons! -->ac <script>in script<\/script> <b>hello</b>";
var config = { ADD_TAGS: ['#comment'], FORCE_BODY: true };
var clean = DOMPurify.sanitize(dirty, config);
console.log("clean => ",clean);
// >>> clean => <!-- I am ready now, click one of the buttons! -->ac  <b>hello</b>