【问题标题】:Allow HTML comments in DomPurify在 DomPurify 中允许 HTML 注释
【发布时间】:2020-04-08 22:07:03
【问题描述】:

我想使用 DOMPurify 清理一些 HTML 内容,但我想保留 HTML cmets。这可能吗?

您可以在 this example 中看到它的作用 - 如果您输入带有评论的标记,则该评论将被删除。

DOMPurify 似乎非常可配置,但 docs 没有提及使用什么术语将 HTML 注释指定为允许的标记。

【问题讨论】:

    标签: javascript html sanitization dompurify


    【解决方案1】:

    我有同样的问题,有一个更好的解决方案,不是messing around with regex in markup(剧透警告:不要!):

    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>
    

    【讨论】:

    • 我比接受的答案更喜欢这个解决方案,但它不适用于 DOMPurify 2.3.6。它将注释的开头 被清理为 \x3C!--hello-->
    【解决方案2】:

    DOMPurify 没有任何钩子或配置来允许 html 字符串中的 cmets。您可以这样做,只需将 &lt;!----&gt; 替换为任何自定义属性并提供配置以允许 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 演示 - http://jsfiddle.net/4j6c28ve/

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2012-01-10
      • 2021-02-28
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多