萬盛學電腦網

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

線上 HTML 編輯器核心原始碼解析:iframe designMode 實作詳解

線上 HTML 編輯器(如 CodePen、JSFiddle、CKEditor 核心)多採用 `iframe + document.designMode = 'on'` 或 `contentEditable` 實現所見即所得編輯。本文解析經典實作原始碼,釐清關鍵 API 與跨瀏覽器注意事項。

核心架構:iframe 隔離編輯環境

<iframe id="editor-frame" style="width: 100%; height: 400px; border: 1px solid #ccc;"></iframe>

<script>
const iframe = document.getElementById('editor-frame');
const doc = iframe.contentDocument || iframe.contentWindow.document;

// 關鍵:啟用設計模式
doc.open();
doc.write('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body></body></html>');
doc.close();

doc.designMode = 'on';           // 整份文件可編輯(舊 API,相容性佳)
// 或
doc.body.contentEditable = true; // 僅 body 可編輯(現代推薦)
</script>

關鍵 API 對照

API層級特性相容性
document.designMode = 'on'文件級整份文件可編輯,含 head、style 等IE5.5+、所有現代瀏覽器
element.contentEditable = true元素級指定元素及其子樹可編輯,控制力更精細IE5.5+、所有現代瀏覽器
document.execCommand()指令bold、italic、insertHTML、createLink 等(已棄用但仍廣泛支援)所有瀏覽器,但規格標準化中
Selection / Range API選區操作現代標準化方式,取代 execCommand現代瀏覽器

常見工具列實作(execCommand 版)

function exec(cmd, value = null) {
  const doc = iframe.contentDocument;
  doc.execCommand(cmd, false, value);
  iframe.contentWindow.focus(); // 保持焦點在編輯區
}

// 工具列按鈕綁定
document.getElementById('btn-bold').onclick = () => exec('bold');
document.getElementById('btn-italic').onclick = () => exec('italic');
document.getElementById('btn-underline').onclick = () => exec('underline');
document.getElementById('btn-link').onclick = () => {
  const url = prompt('輸入連結網址:');
  if (url) exec('createLink', url);
};
document.getElementById('btn-image').onclick = () => {
  const url = prompt('輸入圖片網址:');
  if (url) exec('insertImage', url);
};

取得/設定編輯器內容

// 取得完整 HTML(含 head、body)
function getHTML() {
  return iframe.contentDocument.documentElement.outerHTML;
}

// 僅取得 body 內容(常見需求)
function getBodyHTML() {
  return iframe.contentDocument.body.innerHTML;
}

// 設定內容
function setContent(html) {
  const doc = iframe.contentDocument;
  doc.body.innerHTML = html;
}

跨瀏覽器坑點與對策

問題現象對策
iframe 跨域存取若 iframe src 非同源,`contentDocument` 會拋錯使用 `src="about:blank"` 或同源空白頁,再用 `doc.write()` 注入內容
designMode 在 Firefox 需延遲直接設定無效`setTimeout(() => doc.designMode = 'on', 0)`
Enter 產生 <div> 或 <p> 差異Chrome 產 `
`,Firefox 產 `

`

CSS `div, p { margin: 0; }` 統一樣式,或用 `document.execCommand('defaultParagraphSeparator', false, 'p')`
複製貼上帶入垃圾樣式Word/網頁複製帶 inline style、class監聽 `paste` 事件,用 `clipboardData.getData('text/html')` 清洗後 `insertHTML`
execCommand 棄用MDN 標記 Deprecated,未來可能移除漸進遷移至 Selection/Range API + Input Events

現代化替代方案

理解 iframe designMode 經典實作,有助於閱讀舊專案代碼、除錯相容性問題,也能在評估現代編輯器庫時做出更明智的技術選型。

copyright © 萬盛學電腦網 all rights reserved