<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>
父頁面注入提交攔截器:
<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>
<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: '...'}`。
iframe 嵌入 + 隱藏 textarea 同步 + `postMessage` 跨域通信 + 後端清洗,構成了生產級在線編輯器集成的標準模式。掌握這四大場景,即可覆蓋 95% 的 CMS/表單/郵件/文檔系統需求。