DIV CSS 佈局教程網

KindEditor 的 _formatHtml 為何會吃掉 script 內容,以及怎麼修
編輯:關於JavaScript     

使用 KindEditor 貼上含 <script> 的內容時,腳本裡的程式碼常被不規則地替換或截斷。問題出在它的 HTML 格式化函式 _formatHtml:這個函式會用一堆正則去「美化」標籤,而正則在處理 script 內容時會誤傷到字串裡的 <、> 與換行。本文說明修改思路。

這次改動共處理三件事:修正 script 內容被替換的問題、擴充顏色選擇器(沿用 FCKEditor 的選色方式)、以及為 swfupload 加上上傳前的圖片預覽。

修改後的 _formatHtml

function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
  if (html == null) {
    html = '';
  }

  // 修正:還原被編碼的 textarea 標籤
  html = html.replace(/textarea__/ig, "textarea");

  urlType = urlType || '';
  wellFormatted = _undef(wellFormatted, false);
  indentChar = _undef(indentChar, '\t');
  var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');

  // 關鍵修正:先把 script 內的內容抽出來暫存,用佔位符取代
  // 這樣後續的標籤美化正則就不會破壞腳本內容
  var obj = {};
  var index = 0;
  html = html.replace(/(<script\s[^>]*>)([\s\S]*?)(<\/script>)/ig, function ($0, $1, $2, $3) {
    var value = $2 + '';
    if (value) {
      var key = "{$script__" + index + "$}";
      obj[key] = value;
      index++;
      return $1 + key + $3;
    } else {
      return $0;
    }
  });

  html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function ($0, $1, $2, $3) {
    return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
  });

  html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
  html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
  html = html.replace(/\u200B/g, '');
  html = html.replace(/\u00A9/g, '&copy;');
  html = html.replace(/\u00AE/g, '&reg;');
  html = html.replace(/<[^>]+/g, function ($0) {
    return $0.replace(/\s+/g, ' ');
  });

  var htmlTagMap = {};
  if (htmlTags) {
    _each(htmlTags, function (key, val) {
      var arr = key.split(',');
      for (var i = 0, len = arr.length; i < len; i++) {
        htmlTagMap[arr[i]] = _toMap(val);
      }
    });
    if (!htmlTagMap.script) {
      html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
    }
    if (!htmlTagMap.style) {
      html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
    }
  }

  var re = /(\s*)<(\/)?([\w\-:]+)((?:[^>"']|"[^"]*"|'[^']*')*)(\/)?>(\s*)/g;
  var tagStack = [];

  html = html.replace(re, function ($0, $1, $2, $3, $4, $5, $6) {
    var full = $0,
        startNewline = $1 || '',
        startSlash = $2 || '',
        tagName = $3.toLowerCase(),
        attr = $4 || '',
        endSlash = $5 ? ' ' + $5 : '',
        endNewline = $6 || '';

    if (htmlTags && !htmlTagMap[tagName]) {
      return '';
    }
    if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
      endSlash = ' /';
    }
    if (_INLINE_TAG_MAP[tagName]) {
      if (startNewline) { startNewline = ' '; }
      if (endNewline) { endNewline = ' '; }
    }
    if (_PRE_TAG_MAP[tagName]) {
      if (startSlash) { endNewline = '\n'; } else { startNewline = '\n'; }
    }
    if (wellFormatted && tagName == 'br') {
      endNewline = '\n';
    }
    if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
      if (wellFormatted) {
        if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
          tagStack.pop();
        } else {
          tagStack.push(tagName);
        }
        startNewline = '\n';
        endNewline = '\n';
        for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
          startNewline += indentChar;
          if (!startSlash) { endNewline += indentChar; }
        }
        if (endSlash) {
          tagStack.pop();
        } else if (!startSlash) {
          endNewline += indentChar;
        }
      } else {
        startNewline = endNewline = '';
      }
    }

    if (attr !== '') {
      var attrMap = _getAttrList(full);

      // 把 font 標籤轉成 span + style
      if (tagName === 'font') {
        var fontStyleMap = {}, fontStyle = '';
        _each(attrMap, function (key, val) {
          if (key === 'color') { fontStyleMap.color = val; delete attrMap[key]; }
          if (key === 'size') { fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || ''; delete attrMap[key]; }
          if (key === 'face') { fontStyleMap['font-family'] = val; delete attrMap[key]; }
          if (key === 'style') { fontStyle = val; }
        });
        if (fontStyle && !/;$/.test(fontStyle)) { fontStyle += ';'; }
        _each(fontStyleMap, function (key, val) {
          if (val === '') { return; }
          if (/\s/.test(val)) { val = "'" + val + "'"; }
          fontStyle += key + ':' + val + ';';
        });
        attrMap.style = fontStyle;
      }

      _each(attrMap, function (key, val) {
        if (_FILL_ATTR_MAP[key]) { attrMap[key] = key; }
        if (_inArray(key, ['src', 'href']) >= 0) {
          attrMap[key] = _formatUrl(val, urlType);
        }
        if ((htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key])
            || (tagName === 'body' && key === 'contenteditable')
            || /^kindeditor_\d+$/.test(key)) {
          delete attrMap[key];
        }
        if (key === 'style' && val !== '') {
          var styleMap = _getCssList(val);
          _each(styleMap, function (k, v) {
            if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
              delete styleMap[k];
            }
          });
          var style = '';
          _each(styleMap, function (k, v) { style += k + ':' + v + ';'; });
          attrMap.style = style;
        }
      });

      attr = '';
      _each(attrMap, function (key, val) {
        if (key === 'style' && val === '') { return; }
        val = val.replace(/"/g, '&quot;');
        attr += ' ' + key + '="' + val + '"';
      });
    }

    if (tagName === 'font') { tagName = 'span'; }

    return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
  });

  // pre 內容中的換行要保留
  html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function ($0, $1, $2, $3) {
    return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
  });
  html = html.replace(/\n\s*\n/g, '\n');
  html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');

  // 最後把暫存的 script 內容填回原位
  for (var key in obj) {
    html = html.replace(key, obj[key]);
  }

  return _trim(html);
}

修改原理

核心手法是「先抽出、最後填回」。在進行任何標籤美化之前,先用 /(<script\s[^>]*>)([\s\S]*?)(<\/script>)/ig 把 script 標籤內的內容剪下來,存進 obj 對照表,原位改放 {$script__0$} 這種不可能與真實內容撞名的佔位符。等所有正則都跑完,再把佔位符換回原本的程式碼。這樣格式化邏輯完全看不到 script 內容,自然不會誤傷。

佔位符要選得夠獨特。用 {$script__N$} 這種含特殊符號的形式,是為了避免使用者文字中恰好出現相同字串而被誤替換。若你的內容可能包含自訂格式,建議再加一層隨機前綴。

屬性正則的修正。原本用來比對標籤屬性的正則,遇到屬性值中含 > 的情況(例如 title="a > b")會提早結束。上面把它改成 ((?:[^>"']|"[^"]*"|'[^']*')*),讓引號內的內容整體跳過,是處理 HTML 正則解析的必要防禦。

更根本的建議

用正則處理 HTML 本質上是不可靠的——HTML 不是規則語言,巢狀與引號的組合永遠有漏網案例。上面這些修正能解決眼前問題,但若要長期維護,值得評估:

1. 升級編輯器版本。KindEditor 已停止維護多年,新版 TinyMCE、CKEditor 4/5、Quill 等都有成熟的清單機制與活躍的安全更新。

2. 把 script 完全排除在可編輯範圍外。富文本欄位通常不需要讓使用者寫 JavaScript。透過 editor 的 allowedContent / pasteFilter 機制在貼上時就剝除 script、style、on\* 事件屬性,比事後修格式化函式安全得多。

3. 伺服器端一定要再過濾一次。任何前端過濾都能被繞過(直接打 API 即可)。儲存與輸出時都應經過白名單消毒(例如 OWASP Java HTML Sanitizer 或 DOMPurify 的伺服器端對應方案),避免儲存型 XSS。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved