萬盛學電腦網

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

JavaScript 父頁面與子頁面 (iframe/popup) 雙向傳值完整指南

場景一:window.open 彈出視窗 (同源)

父頁面開啟子視窗

// 父頁面
var childWin = window.open('child.html', 'childWindow', 'width=600,height=400');

// 父 → 子:子視窗載入完成後再傳值 (需監聽 load)
childWin.addEventListener('load', function() {
    childWin.postMessage({ type: 'INIT_DATA', payload: { userId: 123, token: 'abc' } }, '*');
});

// 子 → 父:父頁面監聽 message
window.addEventListener('message', function(e) {
    if (e.source !== childWin) return; // 安全驗證來源
    if (e.data.type === 'FORM_SUBMIT') {
        console.log('收到子頁面資料:', e.data.payload);
        childWin.close();
    }
});

子頁面接收與回傳

// child.html
window.addEventListener('message', function(e) {
    if (e.data.type === 'INIT_DATA') {
        // 初始化表單
        document.getElementById('userId').value = e.data.payload.userId;
    }
});

document.getElementById('submitBtn').addEventListener('click', function() {
    var data = { name: $('#name').val(), email: $('#email').val() };
    window.opener.postMessage({ type: 'FORM_SUBMIT', payload: data }, '*');
    // 或同源直接:window.opener.handleChildData(data);
});

場景二:iframe 內嵌頁面 (同源)

父頁面

<iframe id="childFrame" src="child.html"></iframe>
<button id="sendToChild">發送給子頁面</button>

<script>
var iframe = document.getElementById('childFrame');
iframe.addEventListener('load', function() {
    var childWin = iframe.contentWindow;
    
    // 父 → 子:直接呼叫子頁面暴露的函式 (同源最簡單)
    document.getElementById('sendToChild').onclick = function() {
        childWin.receiveFromParent({ action: 'refresh', timestamp: Date.now() });
    };
    
    // 子 → 父:監聽 postMessage (統一跨域/同源介面)
    window.addEventListener('message', function(e) {
        if (e.source !== childWin) return;
        if (e.data.type === 'CHILD_EVENT') {
            console.log('子頁面事件:', e.data.payload);
        }
    });
});
</script>

子頁面

// 同源:直接掛載函式給父頁面呼叫
window.receiveFromParent = function(data) {
    console.log('收到父頁面:', data);
    if (data.action === 'refresh') location.reload();
};

// 子 → 父:postMessage (同源也建議用此介面,解耦)
function notifyParent(payload) {
    parent.postMessage({ type: 'CHILD_EVENT', payload }, '*');
}

// 表單提交後通知父頁面
$('#form').on('submit', function(e) {
    e.preventDefault();
    $.post('/api/save', $(this).serialize()).done(function(res) {
        notifyParent({ saved: true, id: res.id });
    });
});

場景三:跨域 iframe / popup (postMessage 唯一標準方案)

**雙向皆用 postMessage**,並嚴格驗證 event.origin。

父頁面 (https://parent.com)

const CHILD_ORIGIN = 'https://child.com'; // 固定允許的子域

var iframe = document.getElementById('crossFrame');
iframe.addEventListener('load', () => {
    iframe.contentWindow.postMessage({ type: 'INIT', data: { lang: 'zh-TW' } }, CHILD_ORIGIN);
});

window.addEventListener('message', e => {
    if (e.origin !== CHILD_ORIGIN) return; // 嚴格驗證來源
    if (e.data.type === 'SUBMIT_RESULT') {
        showToast(e.data.payload.success ? '儲存成功' : '儲存失敗');
    }
});

子頁面 (https://child.com)

const PARENT_ORIGIN = 'https://parent.com';

window.addEventListener('message', e => {
    if (e.origin !== PARENT_ORIGIN) return;
    if (e.data.type === 'INIT') {
        initForm(e.data.data.lang);
    }
});

function submitForm(data) {
    fetch('/api/save', { method: 'POST', body: JSON.stringify(data) })
        .then(r => r.json())
        .then(res => {
            parent.postMessage({ type: 'SUBMIT_RESULT', payload: res }, PARENT_ORIGIN);
        });
}

統一通訊協定設計 (建議)

// 訊息格式規範
{
    type: 'ACTION_NAME',        // 必填,大寫底線
    payload: { ... },           // 選填,業務資料
    meta: {                     // 選填,元資料
        requestId: 'uuid',      // 請求追蹤
        timestamp: 1234567890
    }
}

// 封裝通用發送/接收
const Messenger = {
    send(targetWin, type, payload, targetOrigin) {
        targetWin.postMessage({ type, payload, meta: { requestId: uid(), timestamp: Date.now() } }, targetOrigin);
    },
    onMessage(handler, allowedOrigins = ['*']) {
        window.addEventListener('message', e => {
            if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) return;
            handler(e.data, e.origin, e.source);
        });
    }
};

// 使用
Messenger.send(childWin, 'SAVE_FORM', formData, CHILD_ORIGIN);
Messenger.onMessage((data, origin) => {
    if (data.type === 'SAVE_RESULT') handleResult(data.payload);
}, [CHILD_ORIGIN]);

安全檢查清單

  • ✅ 所有 postMessage 發送端指定具體 targetOrigin (非 '*')。
  • ✅ 所有接收端驗證 event.origin 白名單。
  • ✅ 驗證 event.source 是預期的 iframe.contentWindow 或 window.opener。
  • ✅ 敏感操作 (刪除、付款) 需雙向確認,不可單向通知即執行。
  • ✅ CSP 設定 frame-ancestors 限制可嵌入的父頁面域名。
copyright © 萬盛學電腦網 all rights reserved