在 CMS、新聞發佈、部落格後台等場景,嵌入富文本編輯器 (如 CKEditor、TinyMCE、幂編輯器) 是標準需求。本文詳細解析兩種主流嵌入架構 —— Object (IE 專有) 與 Iframe (跨瀏覽器),涵蓋嵌入方式、資料同步提交、圖片上傳整合、編輯模式初始化四大核心環節。
| 維度 | Object (IE Only) | Iframe (跨瀏覽器) |
|---|---|---|
| 嵌入標籤 | <object id="editor" type="text/x-scriptlet" data="editor.html"> | <iframe id="editor" src="editor.html"> |
| 瀏覽器支援 | 僅 IE (ActiveX/Scriptlet 技術) | 所有現代瀏覽器 |
| 資料取得 | editor.value 或 editor.getHTML() | editor.contentWindow.getHTML() 或 postMessage |
| 安全性 | 較低 (ActiveX 攻擊面) | 標準沙箱模型,可加 sandbox |
| 現代建議 | 棄用 | 首選 |
無論哪種嵌入方式,表單提交時需將編輯器 HTML 同步至隱藏 <textarea>:
<form id="contentForm" method="post" action="/save" onsubmit="return syncEditor()">
<!-- 編輯器嵌入點 -->
<iframe id="editor" src="/editor.html" style="width:100%; height:400px; border:1px solid #ddd;"></iframe>
<!-- 隱藏欄位:實際提交給後端 -->
<textarea name="content" id="hiddenContent" style="display:none;"></textarea>
<button type="submit">發佈</button>
</form>
<script>
function syncEditor() {
const editorFrame = document.getElementById('editor');
const hidden = document.getElementById('hiddenContent');
// 方案 A:編輯器暴露全域 getHTML() 方法 (同域)
if (editorFrame.contentWindow && editorFrame.contentWindow.getHTML) {
hidden.value = editorFrame.contentWindow.getHTML();
return true;
}
// 方案 B:postMessage 跨域通訊
editorFrame.contentWindow.postMessage({ action: 'getHTML' }, '*');
// 需配合異步回調,表單提交改為 AJAX
return false;
}
</script>
用戶點擊編輯器「插入圖片」按鈕
↓
彈出上傳對話框 (獨立頁面/Modal) → 選擇本地圖片 → 上傳至伺服器
↓
伺服器返回圖片 URL (如 /uploads/abc123.jpg)
↓
父頁面/編輯器插入 <img src="/uploads/abc123.jpg"> 至光標位置
<iframe id="editor" src="/editor.html"></iframe>
<script>
// 父頁面暴露插入圖片 API,供上傳頁面調用
function insertImageToEditor(imgUrl, alt = '') {
const editorWin = document.getElementById('editor').contentWindow;
if (editorWin && editorWin.insertHTML) {
editorWin.insertHTML(`<img src="${imgUrl}" alt="${alt}">`);
}
}
// 接收上傳頁面 postMessage (更安全)
window.addEventListener('message', (e) => {
if (e.data.action === 'insertImage' && e.data.url) {
insertImageToEditor(e.data.url, e.data.alt);
}
});
</script>
<form id="uploadForm" enctype="multipart/form-data" target="uploadTarget">
<input type="file" name="image" accept="image/*" required>
<button type="submit">上傳</button>
</form>
<iframe name="uploadTarget" style="display:none;"></iframe>
<script>
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const res = await fetch('/api/upload', { method: 'POST', body: formData });
const { url, success } = await res.json();
if (success) {
// 方式 1:直接調用父頁面函數 (同域)
// window.opener.insertImageToEditor(url);
// window.close();
// 方式 2:postMessage (跨域友善)
window.parent.postMessage({ action: 'insertImage', url, alt: '' }, '*');
window.close();
}
});
</script>
<iframe id="editbox" src="blank.html" style="width:100%; height:100%;"></iframe>
<script>
// 編輯器初始化:設計模式開啟
const editDoc = document.getElementById('editbox').contentDocument;
editDoc.designMode = 'on';
editDoc.write('<html><body></body></html>');
editDoc.close();
// 對外暴露 API
window.getHTML = () => editDoc.body.innerHTML;
window.setHTML = (html) => { editDoc.body.innerHTML = html; };
window.insertHTML = (html) => {
editDoc.defaultView.focus();
const sel = editDoc.defaultView.getSelection();
if (sel.rangeCount > 0) {
const range = sel.getRangeAt(0);
range.deleteContents();
const frag = editDoc.createRange().createContextualFragment(html);
range.insertNode(frag);
}
};
</script>
<body onload="loadContent()">
<textarea id="dbContent" style="display:none;"><%= Server.HTMLEncode(rs("Content")) %></textarea>
<iframe id="editor" src="/editor.html"></iframe>
<script>
function loadContent() {
const content = document.getElementById('dbContent').value;
const editorWin = document.getElementById('editor').contentWindow;
if (editorWin && editorWin.setHTML) {
editorWin.setHTML(content);
}
}
</script>
關鍵點:使用 <textarea style="display:none"> 而非 <input type="hidden">,因編輯器內容含換行,hidden input 會截斷導致 HTML 結構破壞。
手工維護編輯器成本極高 (跨瀏覽器相容、安全過濾、粘貼清理、表格操作、無障礙...)。強烈建議整合成熟開源方案:
| 編輯器 | 特色 | 授權 | 整合複雜度 |
|---|---|---|---|
| TinyMCE | 功能最全、插件豐富、商業支援好 | LGPL/商業 | 低 (CDN 一鍵引入) |
| CKEditor 5 | 現代架構、協同編輯、TypeScript 原生 | GPL/商業 | 中 (模組化配置) |
| Quill | 輕量、模組化、API 優雅 | BSD | 低 |
| Slate / ProseMirror | 框架級、極致可定制、需自行組裝 | MIT | 高 (適合複雜文檔應用) |
| Editor.js | 區塊式、輸出 JSON、適合結構化內容 | MIT | 低 |