父頁面 A 通過 showModalDialog 打開模態窗口 B,B 完成操作後關閉並刷新 A。
// 父頁面 A
function openModal() {
// showModalDialog 會阻塞執行,返回時子窗口已關閉
window.showModalDialog('b.html', window,
'dialogWidth:400px;dialogHeight:500px;center:yes;status:no');
// 代碼阻塞在此,子窗口關閉後繼續執行
window.location.reload(); // 刷新父頁面
}
⚠️ showModalDialog 已從 HTML 標準移除,Chrome 37+、Firefox、Edge 均不支援,僅限 IE/舊版 Edge 維護項目使用。
// 父頁面 A
function openModalModern() {
const child = window.open('b.html', '_blank', 'width=400,height=500');
// 監聽子頁面消息
window.addEventListener('message', function(e) {
// 安全性:驗證來源
if (e.origin !== location.origin) return;
if (e.data === 'child:completed') {
window.location.reload();
child.close(); // 關閉子窗口
}
});
}
// 子頁面 B
function submitAndClose() {
// 提交數據...
fetch('/api/submit', { method: 'POST', body: data })
.then(() => {
// 通知父頁面
window.opener.postMessage('child:completed', location.origin);
window.close();
});
}
// 父頁面
// 子頁面
parent.postMessage('close:modal', '*');
現代框架(Vue/React/Angular)不使用彈窗,改用:
| 方案 | 支援瀏覽器 | 跨域 | 推薦度 |
|---|---|---|---|
| showModalDialog | IE only | 同域 | ❌ 棄用 |
| window.open + postMessage | 所有現代瀏覽器 | 支援跨域 | ✅ 推薦 |
| iframe + postMessage | 所有現代瀏覽器 | 支援跨域 | ✅ 推薦 |
| SPA 組件模態框 | 所有現代瀏覽器 | 同域(單應用) | ✅ 最佳 |