萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 關閉模態窗口並刷新父頁面的實現方案

場景

父頁面 A 通過 showModalDialog 打開模態窗口 B,B 完成操作後關閉並刷新 A。

方案一:父頁面輪詢檢測(showModalDialog 特有)


// 父頁面 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 維護項目使用。

方案二:現代方案 - window.open + postMessage


// 父頁面 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();
        });
}

方案三:iframe 模態框(同域嵌入)


// 父頁面




// 子頁面
parent.postMessage('close:modal', '*');

方案四:單頁應用(SPA)路由/狀態管理

現代框架(Vue/React/Angular)不使用彈窗,改用:

  • 路由守衛 + 組件狀態
  • Modal 組件(Portal 渲染到 body)
  • 狀態管理庫同步數據,無需刷新頁面

兼容性總結表

方案支援瀏覽器跨域推薦度
showModalDialogIE only同域❌ 棄用
window.open + postMessage所有現代瀏覽器支援跨域✅ 推薦
iframe + postMessage所有現代瀏覽器支援跨域✅ 推薦
SPA 組件模態框所有現代瀏覽器同域(單應用)✅ 最佳
copyright © 萬盛學電腦網 all rights reserved