Search code examples
javascripthtmlsanitizationdompurify

Allow HTML comments in DomPurify


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.


Solution

  • 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/