DOMPurify 前端富文本 XSS 防护使用指南
安装依赖
使用 npm 安装 DOMPurify 库:
bash
npm install dompurify
对于 TypeScript 项目,需额外安装类型声明:
bash
npm install @types/dompurify -D
引入库
在项目中引入 DOMPurify:
js
import DOMPurify from 'dompurify';
核心净化方法
使用 sanitize 方法对原始 HTML 进行净化:
js
const safeHtml = DOMPurify.sanitize(content);
Vue 项目集成
直接使用模板内净化
vue
<template>
<div v-html="DOMPurify.sanitize(content)"></div>
</template>
<script setup>
import { ref } from 'vue'
import DOMPurify from 'dompurify'
const content = ref('<p>博客正文</p><script>恶意脚本</script>')
</script>
使用计算属性优化性能
vue
<template>
<div v-html="safeContent"></div>
</template>
<script setup>
import { ref, computed } from 'vue'
import DOMPurify from 'dompurify'
const content = ref('后端返回的原始富文本')
const safeContent = computed(() => DOMPurify.sanitize(content.value))
</script>
自定义配置
通过配置白名单控制允许的标签和属性:
js
const safeContent = computed(() => {
return DOMPurify.sanitize(content.value, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'h1', 'h2', 'ul', 'ol', 'li', 'a', 'img'],
ALLOWED_ATTR: ['src', 'alt', 'href', 'class', 'title'],
ALLOW_UNKNOWN_PROTOCOLS: false
})
})
拦截的 XSS 风险
DOMPurify 自动清除以下恶意内容:
<script>标签- 所有内联事件(如
onclick,onerror) - 危险链接协议(如
javascript:,vbscript:) - 恶意 iframe 和 svg 注入
安全提醒
- 禁止直接渲染未净化的 HTML 内容
- 前端过滤需配合后端二次净化
- DOMPurify 默认配置已足够安全,无需手动编写正则
核心原则
- 所有用户输入的 HTML 必须经过净化后才能渲染
- 净化流程:安装 → 引入 → 调用
sanitize()→ 安全渲染 - 作用:清除恶意脚本,保留合法排版标签