You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何sanitize与sanitizeforCards会移除span的color样式?

为什么sanitize-html会移除span的color样式属性?

我使用sanitize-html库清理HTML时,发现<span style="color: rgb(230, 0, 0);">SAMPLE text</span>被清理后变成了<span>SAMPLE text</span>,sanitize和sanitizeforCards两个配置都移除了span的color样式属性。我的配置代码如下:

import sanitizeHtml from 'sanitize-html'

const sanitizerConfig = {
  allowedTags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'div', 'b', 'i', 'strong', 'em', 'span', 'ul', 'ol', 'li', 'a',
    'u', 's', 'br'],
  allowedAttributes: {
    a: ['href', 'target', 'style'],
    span: ['style'],
    h1: ['style'],
    h2: ['style'],
    h3: ['style'],
    h4: ['style'],
    h5: ['style'],
    h6: ['style'],
    p: ['style'],
    div: ['style'],
    b: ['style'],
    i: ['style'],
    strong: ['style'],
    em: ['style'],
    ul: ['style'],
    ol: ['style'],
    li: ['style'],
    u: ['style'],
    s: ['style']
  },
  allowedStyles: {
    '*': {
      'text-align': [/^left$/, /^right$/, /^center$/]
    },
    span: {
      'text-decoration': [/^underline$/],
      color: true
    }
  }
}
const sanitizerConfigForCards = {
  allowedTags: ['p', 'div', 'b', 'i', 'strong', 'em', 'span', 'ul', 'ol', 'li'],
  allowedAttributes: {
    span: ['style']
  },
  allowedStyles: {
    span: {
      color: true
    }
  }
}

export const sanitize = (content) => sanitizeHtml(content, sanitizerConfig)
/** Sanitizes user-generated html content for displaying it inside of card components. */
export const sanitizeforCard = (content) => sanitizeHtml(content, sanitizerConfigForCards)

原因分析

问题出在sanitize-html对颜色值的默认校验规则上:

  • 当你在allowedStyles里将color设为true时,库只会允许命名颜色(如red、blue)和十六进制颜色(如#e60000);
  • RGB/RGBA格式的颜色值(如rgb(230, 0, 0))不在默认允许的范围内,因此会被自动过滤。

解决方案

要允许RGB(包括RGBA)格式的颜色,需要给color配置一个匹配该格式的正则表达式。修改两个配置的allowedStyles部分即可:

修改后的sanitizerConfig

const sanitizerConfig = {
  // ... 其他配置不变
  allowedStyles: {
    '*': {
      'text-align': [/^left$/, /^right$/, /^center$/]
    },
    span: {
      'text-decoration': [/^underline$/],
      // 匹配RGB/RGBA、十六进制、命名颜色
      color: [
        /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/,
        /^rgba\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(0|1|0\.\d+)\s*\)$/,
        /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
        /^[a-zA-Z]+$/
      ]
    }
  }
}

修改后的sanitizerConfigForCards

const sanitizerConfigForCards = {
  // ... 其他配置不变
  allowedStyles: {
    span: {
      // 同样匹配RGB/RGBA、十六进制、命名颜色
      color: [
        /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/,
        /^rgba\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(0|1|0\.\d+)\s*\)$/,
        /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
        /^[a-zA-Z]+$/
      ]
    }
  }
}

这样修改后,rgb(230, 0, 0)这类颜色值就会被保留下来,不会被清理器移除。

内容的提问来源于stack exchange,提问作者krltos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 08:33:38