简体   繁体   English

在 DomPurify 中允许 HTML 注释

[英]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.我想使用 DOMPurify 来清理一些 HTML 内容,但我想保留 HTML 注释。 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. DOMPurify 似乎非常可配置,但文档没有提到使用什么术语将 HTML 注释指定为允许的标签。

DOMPurify doesn't have any hooks or configuration to allow comments in html string. DOMPurify没有任何钩子或配置来允许 html 字符串中的注释。 You can do one this just replace the <!-- and --> to any custom attribute and provide configuration to allow ADD_TAGS: ['comment'] it.您可以这样做,只需将<!---->替换为任何自定义属性并提供配置以允许ADD_TAGS: ['comment']它。

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/ jsFiddle 演示 - http://jsfiddle.net/4j6c28ve/

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM