萬盛學電腦網

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

HTML 在線編輯器實戰集成指南:iframe 嵌入、數據雙向綁定、圖片上傳、編輯現有內容四大核心場景

場景一:iframe 嵌入編輯器 (現代標準)

<form id="articleForm" method="post" action="/save">
  <iframe id="editorFrame" src="/static/editor/index.html" 
          style="width:100%; height:500px; border:1px solid #ddd; border-radius:4px;"></iframe>
  <textarea name="content" id="hiddenContent" style="display:none;"></textarea>
  <button type="submit">發布文章</button>
</form>

場景二:提交前獲取編輯器 HTML 內容

父頁面注入提交攔截器:

<script>
document.getElementById('articleForm').addEventListener('submit', function(e) {
  const iframe = document.getElementById('editorFrame');
  try {
    // 同域直接訪問
    const html = iframe.contentDocument.body.innerHTML;
    document.getElementById('hiddenContent').value = html;
  } catch (err) {
    // 跨域需 postMessage
    console.error('跨域無法直接讀取', err);
  }
});
</script>

編輯器頁面需暴露獲取方法 (跨域時):

<script>
// editor/index.html
window.parent.postMessage({ type: 'READY' }, '*'); // 通知父頁面就緒
window.addEventListener('message', (e) => {
  if (e.data.type === 'GET_CONTENT') {
    e.source.postMessage({ type: 'CONTENT', html: document.body.innerHTML }, e.origin);
  }
});
</script>

場景三:工具欄「插入圖片」→ 本地上傳 → 插入編輯器

  1. 編輯器工具欄按鈕綁定:``
  2. 彈出上傳頁面:`window.open('/upload?callback=insertImage', 'uploadWin', 'width=500,height=300')`
  3. 上傳頁面上傳成功後調用父頁面函數:
<script>
// 父頁面 (文章編輯頁)
function insertImage(url) {
  const iframe = document.getElementById('editorFrame');
  iframe.contentWindow.focus();
  // 現代方式:execCommand 已棄用但仍通用
  iframe.contentDocument.execCommand('insertImage', false, url);
  // 或直接操作選區 (更穩健)
  const sel = iframe.contentWindow.getSelection();
  if (sel.rangeCount) {
    const range = sel.getRangeAt(0);
    const img = iframe.contentDocument.createElement('img');
    img.src = url;
    range.insertNode(img);
    range.collapseAfter(img);
  }
}
</script>

上傳頁面:`window.opener.insertImage('https://cdn.example.com/img/abc.jpg'); window.close();`

場景四:編輯現有文章 — 回填數據庫內容到編輯器

<iframe id="editorFrame" src="/static/editor/index.html"></iframe>
<script>
// 頁面加載完成後回填
window.addEventListener('load', function() {
  const initialHtml = '<p>這是從數據庫讀取的現有內容...</p>'; // 服務端模板注入或 AJAX 獲取
  const iframe = document.getElementById('editorFrame');
  // 等待編輯器就緒 (簡易輪詢)
  const checkReady = setInterval(() => {
    try {
      if (iframe.contentDocument.readyState === 'complete') {
        clearInterval(checkReady);
        iframe.contentDocument.body.innerHTML = initialHtml;
      }
    } catch (e) { /* 跨域忽略 */ }
  }, 100);
});
</script>

**跨域最佳實踐**:編輯器頁面監聽 `message` 事件,父頁面發送 `{type: 'SET_CONTENT', html: '...'}`。

安全與工程化清單

  • ✅ **XSS 清洗**:後端存儲前、前端渲染前雙重 `DOMPurify.sanitize(html, {ALLOWED_TAGS: [...]})`。
  • ✅ **CSP**:`Content-Security-Policy: script-src 'self'; frame-src 'self' https://cdn.example.com;`。
  • ✅ **沙箱**:`