子視窗(透過 window.open() 開啟)需要觸發父視窗的函式,例如:子視窗完成資料編輯後,通知父視窗重新整理列表或更新標題。
window.opener 取得父視窗的 window 物件參考。window 物件)。<!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>
<!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 同步狀態 |
跨域或更安全的通訊方式:
// 父視窗
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 以支援跨域並提升安全性。實作時務必加入存在性檢查與錯誤處理,避免因視窗關閉或跨域導致腳本中斷。