0

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.

And Finally
  • 5,602
  • 14
  • 70
  • 110

2 Answers2

2

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>
Lasse
  • 411
  • 4
  • 15
  • 1
    I like this solution better than the accepted answer, except it isn't working for me with DOMPurify 2.3.6. It's encoding the opening < of the comment as \x3C so that is sanitized to \x3C!--hello--> – bmode Apr 16 '22 at 23:50
0

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/

front_end_dev
  • 1,998
  • 1
  • 9
  • 14