線上 HTML 編輯器(如 CodePen、JSFiddle、CKEditor 核心)多採用 `iframe + document.designMode = 'on'` 或 `contentEditable` 實現所見即所得編輯。本文解析經典實作原始碼,釐清關鍵 API 與跨瀏覽器注意事項。
<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 | 層級 | 特性 | 相容性 |
|---|---|---|---|
document.designMode = 'on' | 文件級 | 整份文件可編輯,含 head、style 等 | IE5.5+、所有現代瀏覽器 |
element.contentEditable = true | 元素級 | 指定元素及其子樹可編輯,控制力更精細 | IE5.5+、所有現代瀏覽器 |
document.execCommand() | 指令 | bold、italic、insertHTML、createLink 等(已棄用但仍廣泛支援) | 所有瀏覽器,但規格標準化中 |
Selection / Range API | 選區操作 | 現代標準化方式,取代 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 經典實作,有助於閱讀舊專案代碼、除錯相容性問題,也能在評估現代編輯器庫時做出更明智的技術選型。