// 父頁面
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 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 });
});
});
**雙向皆用 postMessage**,並嚴格驗證 event.origin。
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 ? '儲存成功' : '儲存失敗');
}
});
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。frame-ancestors 限制可嵌入的父頁面域名。