萬盛學電腦網

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

JavaScript 跨視窗呼叫父視窗函式完整教學

應用場景

子視窗(透過 window.open() 開啟)需要觸發父視窗的函式,例如:子視窗完成資料編輯後,通知父視窗重新整理列表或更新標題。

核心原理

  • 子視窗透過 window.opener 取得父視窗的 window 物件參考。
  • 父視窗必須在全域範圍定義可被呼叫的函式(掛載於 window 物件)。
  • 同源策略限制:父子視窗必須同源(協定、域名、埠相同),否則會拋出安全性錯誤。

完整程式碼範例

父視窗 (parent.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>父視窗</title>
</head>
<body>
    <div>
        <button id="btnOpenChild">開啟子視窗</button>
    </div>

    <script>
        // 全域函式,供子視窗呼叫
        function show() {
            document.title = '父視窗更新於 ' + new Date().toLocaleTimeString();
            console.log('父視窗 show() 被呼叫');
        }

        window.onload = function() {
            var btn = document.getElementById('btnOpenChild');
            btn.onclick = function() {
                try {
                    window.open('child.html', 'childWindow', 'width=400,height=300');
                } catch (e) {
                    alert('開啟視窗失敗:' + e.message);
                }
            };
        };
    </script>
</body>
</html>

子視窗 (child.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>子視窗</title>
</head>
<body>
    <button id="btnNotifyParent">通知父視窗更新</button>

    <script>
        document.getElementById('btnNotifyParent').onclick = function() {
            if (window.opener && !window.opener.closed) {
                try {
                    window.opener.show(); // 呼叫父視窗的 show()
                } catch (e) {
                    console.error('跨視窗呼叫失敗(可能跨域):', e);
                    alert('無法呼叫父視窗函式,請檢查同源策略');
                }
            } else {
                alert('父視窗已關閉或不存在');
            }
        };
    </script>
</body>
</html>

進階應用:傳遞參數與回傳值

// 父視窗
function updateData(data) {
    console.log('收到子視窗資料:', data);
    // 更新 UI...
    return '父視窗處理完成';
}

// 子視窗
function sendToParent() {
    if (window.opener && typeof window.opener.updateData === 'function') {
        var result = window.opener.updateData({ id: 123, name: '測試資料' });
        console.log('父視窗回傳:', result);
    }
}

常見問題與解決方案

問題原因解決方案
window.opener 為 null非 window.open() 開啟(如 target="_blank" 且有 rel="noopener")確保使用 window.open();若需 noopener,改用 postMessage 通訊
「Permission denied」或「Blocked a frame with origin...」跨域(不同域名/埠/協定)改用 window.postMessage() 跨域通訊
父視窗函式未定義函式未掛載於 window(如模組化寫法、IIFE 內部)改用 window.show = function() {...} 明確掛載
父視窗已重新整理/導頁opener 指向舊 window 實例,函式已不存在子視窗檢查 opener.closed,或改用 localStorage/BroadcastChannel 同步狀態

現代替代方案:postMessage

跨域或更安全的通訊方式:

// 父視窗
window.addEventListener('message', function(event) {
    if (event.origin !== 'https://trusted-child-domain.com') return;
    if (event.data.type === 'UPDATE_TITLE') {
        document.title = event.data.payload;
    }
});

// 子視窗
window.opener.postMessage({
    type: 'UPDATE_TITLE',
    payload: '來自子視窗的更新 ' + new Date().toISOString()
}, 'https://parent-domain.com'); // 指定目標 origin

總結

window.opener 是同源父子視窗通訊的傳統且直觀方式。現代開發建議優先考慮 postMessage 以支援跨域並提升安全性。實作時務必加入存在性檢查與錯誤處理,避免因視窗關閉或跨域導致腳本中斷。

copyright © 萬盛學電腦網 all rights reserved