在前端處理使用者輸入或第三方 HTML 內容時,必須進行淨化以防止 XSS 攻擊。本文系統比較四種主流方案:`DOMParser` 原生解析、專業庫 DOMPurify、正則表達式、以及 `innerText`/`textContent` 純文字提取,分析安全性、效能、適用場景,提供生產級最佳實踐代碼。
function sanitizeHtmlNative(html, allowedTags = ['p', 'b', 'i', 'strong', 'em', 'br', 'ul', 'ol', 'li', 'a', 'img']) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 遞迴清理節點
function cleanNode(node) {
if (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.COMMENT_NODE) return;
if (node.nodeType === Node.ELEMENT_NODE) {
const tagName = node.tagName.toLowerCase();
// 移除不在白名單的標籤 (保留子節點)
if (!allowedTags.includes(tagName)) {
const fragment = document.createDocumentFragment();
while (node.firstChild) fragment.appendChild(node.firstChild);
node.parentNode.replaceChild(fragment, node);
return; // 節點已被替換,不再處理子節點
}
// 清理屬性:僅保留安全屬性
const allowedAttrs = ['href', 'src', 'alt', 'title', 'width', 'height', 'class', 'id', 'style'];
[...node.attributes].forEach(attr => {
if (!allowedAttrs.includes(attr.name)) node.removeAttribute(attr.name);
// 額外驗證 href/src 協定
if (['href', 'src'].includes(attr.name)) {
const url = attr.value.trim().toLowerCase();
if (url.startsWith('javascript:') || url.startsWith('data:') || url.startsWith('vbscript:')) {
node.removeAttribute(attr.name);
}
}
});
// 遞迴處理子節點
[...node.childNodes].forEach(cleanNode);
}
}
cleanNode(doc.body);
return doc.body.innerHTML;
}
// 使用範例
const dirty = '<p>正常</p><script>alert(1)</script><img src=x onerror=alert(1)><a href="javascript:alert(1)">連結</a>';
console.log(sanitizeHtmlNative(dirty));
// 輸出:<p>正常</p><img src="x" alt=""><a>連結</a>
npm install dompurify
// 或 CDN
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>
import DOMPurify from 'dompurify';
const dirty = '<p>正常</p><script>alert(1)</script><img src=x onerror=alert(1)><a href="javascript:alert(1)">連結</a>';
const clean = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['p', 'b', 'i', 'strong', 'em', 'br', 'ul', 'ol', 'li', 'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'caption'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'width', 'height', 'class', 'id', 'style', 'scope', 'colspan', 'rowspan'],
ALLOWED_URI_REGEXP: /^(?:https?|mailto|tel):/i, // 僅允許 http/https/mailto/tel 協定
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'style'], // 可選禁用 style
KEEP_CONTENT: true // 移除標籤但保留內容
});
console.log(clean);
// 輸出:<p>正常</p><img src="x" alt=""><a href="#">連結</a>
const { JSDOM } = require('jsdom');
const DOMPurify = require('dompurify')(new JSDOM('').window);
const clean = DOMPurify.sanitize(dirtyHtml, config); // 同瀏覽器配置
// 移除所有標籤 (極度危險)
function stripTagsRegex(html) {
return html.replace(/<[^>]*>/g, '');
}
// 提取連結 href (脆弱,不建議)
function extractLinksRegex(html) {
const regex = /<a\s+[^>]*href\s*=\s*["']([^"']+)["'][^>]*>/gi;
const links = [];
let match;
while ((match = regex.exec(html)) !== null) links.push(match[1]);
return links;
}
// 移除 script 標籤及內容
function removeScriptsRegex(html) {
return html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
}
⚠️ **正則處理 HTML 的致命缺陷**:無法處理巢狀、屬性值含 `>`、註解/CDATA、實體編碼繞過、Unicode 正規化繞過、災難性回溯。**生產環境嚴禁。**
const dirty = '<p>正常</p><script>alert(1)</script><b>粗體</b>';
// 建立臨時容器 (離螢幕,不觸發重排)
const temp = document.createElement('div');
temp.innerHTML = dirty;
// 取得純文字 (移除所有標籤、解碼實體)
const plainText = temp.innerText; // 或 temp.textContent (保留換行/空白差異)
console.log(plainText); // "正常alert(1)粗體"
// 取得純文字並保留換行結構
function getTextWithLineBreaks(html) {
const temp = document.createElement('div');
temp.innerHTML = html;
// 將區塊元素轉為換行
temp.querySelectorAll('div, p, br, li, tr, td, th, h1, h2, h3, h4, h5, h6, blockquote').forEach(el => {
if (el.tagName === 'BR') el.replaceWith('\n');
else el.insertAdjacentText('afterend', '\n');
});
return temp.innerText.trim();
}
適用場景:搜尋索引、預覽摘要、儲存純文字版本。**不適用於需要保留 HTML 結構的輸出。**
| 維度 | DOMParser 原生 | DOMPurify | 正則表達式 | innerText/textContent |
|---|---|---|---|---|
| 安全性 (XSS 防禦) | 高 (需自行實作白名單/協定檢查) | **極高** (標準化、持續更新、CSP 相容) | 極低 (極易繞過) | 極高 (輸出純文字,零 HTML 風險) |
| HTML 結構保留 | ✅ 可配置白名單保留 | ✅ 完整白名單引擎 | ❌ 破壞結構 | ❌ 完全移除 |
| 效能 | 中 (原生解析器) | 中 (快取優化後極快) | 快 (但風險高) | **極快** |
| 依賴 | 零 | ~15KB gzipped | 零 | 零 |
| Node.js 支援 | 需 JSDOM | 原生支援 (需 JSDOM) | ✅ | 需 JSDOM |
| 適用場景 | 無法引入依賴、簡單白名單、學習用途 | **所有生產環境 UGC、CMS、編輯器、郵件、API 回應** | 教學、極受控原型 | 搜尋索引、摘要、純文字儲存 |
// utils/sanitize.js
import DOMPurify from 'dompurify';
// 場景化配置
const configs = {
comment: { // 留言、評論
ALLOWED_TAGS: ['p', 'b', 'i', 'strong', 'em', 'br', 'a', 'img'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title'],
ALLOWED_URI_REGEXP: /^(?:https?|mailto):/i
},
article: { // 文章內容
ALLOWED_TAGS: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b', 'i', 'strong', 'em', 'br', 'ul', 'ol', 'li', 'a', 'img', 'blockquote', 'pre', 'code', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'caption', 'hr'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'width', 'height', 'class', 'id', 'style', 'scope', 'colspan', 'rowspan'],
ALLOWED_URI_REGEXP: /^(?:https?|mailto|tel):/i
},
strict: { // 僅純文字標記
ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em'],
ALLOWED_ATTR: []
}
};
export function sanitize(html, scene = 'comment') {
const config = configs[scene] || configs.comment;
return DOMPurify.sanitize(html, config);
}
// 使用
import { sanitize } from '@/utils/sanitize';
const safeHtml = sanitize(userInput, 'article');
即使 HTML 已淨化,**仍必須部署 CSP** 作為纵深防禦:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{random}';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' data:;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
前端 HTML 淨化**首選 DOMPurify**,零配置即具備企業級安全性,支援瀏覽器/Node/Worker,積極維護且廣泛採用。`DOMParser` 原生方案適合無法引入依賴的受限環境,但需自行完善白名單與協定檢查。正則表達式**嚴禁生產使用**。`innerText` 適用於純文字提取場景。建立專案統一的 `sanitize(html, scene)` 服務,配合 CSP,構建纵深 XSS 防禦體系。