萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 移除 HTML 標籤實戰技巧:DOMParser、regex 與安全性考量

前端移除 HTML 標籤的常見場景

用戶輸入內容顯示於非 HTML 區域(如文字輸入框、彈窗、匯出純文字)、防止 XSS、資料清洗前送後端。前端處理屬「第二道防線」,**後端輸出編碼才是核心防護**。

方案一:DOMParser(推薦、安全、標準)

function stripTags(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || '';
}

// 測試
stripTags('<p>Hello <b>World</b></p><script>alert(1)</script>');
// 回傳 "Hello Worldalert(1)"(腳本內容也會被保留為文字)

優點:瀏覽器原生解析、正確處理巢狀/破損標籤、不執行腳本。缺點:IE 需 polyfill、會保留 <script>/<style> 內容。

方案二:建立暫存元素(輕量、相容性佳)

function stripTags(html) {
  const div = document.createElement('div');
  div.innerHTML = html;
  return div.textContent || div.innerText || '';
}

注意:innerHTML 設定時**不會執行** <script>,但舊版 IE 有風險。現代瀏覽器安全。

方案三:正則表達式(不推薦用於生產環境)

// 簡單版:無法處理屬性含 >、註解、CDATA、破損標籤
function stripTagsRegex(html) {
  return html.replace(/<[^>]*>/g, '');
}

// 較完整版(仍有邊界案例)
function stripTagsRegexAdvanced(html) {
  return html
    .replace(/<!--[\s\S]*?-->/g, '')           // 移除註解
    .replace(/<script[\s\S]*?<\/script>/gi, '') // 移除 script 區塊
    .replace(/<style[\s\S]*?<\/style>/gi, '')   // 移除 style 區塊
    .replace(/<[^>]*>/g, '');                  // 移除剩餘標籤
}

警告:HTML 非正則語言,regex 無法完整解析巢狀、屬性引號跳脫、條件註解等。**生產環境請勿依賴 regex**。

進階需求:保留特定標籤(如允許 <b><i><a>)

function stripTagsAllow(html, allowedTags = ['b', 'i', 'a', 'strong', 'em']) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const walker = document.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT);
  const toRemove = [];
  while (walker.nextNode()) {
    if (!allowedTags.includes(walker.currentNode.tagName.toLowerCase())) {
      toRemove.push(walker.currentNode);
    }
  }
  toRemove.forEach(el => el.replaceWith(...el.childNodes));
  return doc.body.innerHTML;
}

安全性關鍵提醒

  1. 前端過濾 ≠ 資安防護:攻擊者可繞過前端直接呼叫 API。後端**必須**做輸出編碼。
  2. innerHTML 設定雖不執行 script,但 <img onerror>、<svg onload> 等事件處理器**可能觸發**
  3. 使用 textContent 而非 innerText(後者觸發重排、受 CSS 影響)
  4. DOMPurify 是業界標準函式庫,支援允許清單、Shadow DOM、Server-side (Node.js)

推薦生產級方案:DOMPurify

// npm install dompurify
import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(dirtyHTML, {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
  ALLOWED_ATTR: ['href', 'target', 'rel']
});

// 只保留純文字
const textOnly = DOMPurify.sanitize(dirtyHTML, { ALLOWED_TAGS: [] });

前端移除標籤以 DOMParser 或 DOMPurify 為主,配合後端情境化編碼,構建完整防禦深度。切記:任何來自使用者的 HTML 內容,預設視為惡意處理。

copyright © 萬盛學電腦網 all rights reserved