通信原理
- 父 → 子:URL 參數傳遞(
window.open('child.html?param=value')),子頁面通過 location.search 解析。
- 子 → 父:調用父窗口全局函數(
window.opener.parentFunc(data))。
完整示例
父頁面 (index.html)
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Parent</title></head><body>
<div id="content"></div>
<button id="test">打開子窗口</button>
<script>
document.getElementById('test').onclick = function(){
window.open('./window.html?param1=name¶m2=password', '_blank',
'width=960,height=650,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes');
};
// 供子窗口調用的全局函數
window.getContent = function(tx){
document.getElementById('content').innerText = tx;
};
</script></body></html>
子頁面 (window.html)
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Child</title></head><body>
<div id="content"></div>
<select id="city">
<option value="shanghai">上海</option>
<option value="hangzhou">杭州</option>
</select>
<script>
// 解析 URL 參數
var params = location.href.substring(location.href.lastIndexOf('?')+1).split('&');
document.getElementById('content').innerText = params;
var city = document.getElementById('city');
city.onchange = function(){
// 調用父窗口函數傳回選中值
window.opener.getContent(city.value);
};
</script></body></html>
注意事項
- 必須在 **HTTP/HTTPS 服務** 下運行(
file:// 協議下 opener 可能為 null 或跨域報錯)。
- 同源策略:父子頁面必須同域(協議、域名、端口一致),否則
opener 訪問受限。
- 子窗口關閉後
opener 仍存在,但屬性可能不可訪問,建議檢查 if(window.opener && !window.opener.closed)。
- 現代替代:
postMessage 跨域安全通信(見下文)。
跨域安全方案:postMessage
// 父頁面
window.addEventListener("message", function(e){
if(e.origin !== "https://child.example.com") return; // 驗證來源
document.getElementById("content").innerText = e.data;
}, false);
// 子頁面
window.opener.postMessage(selectedValue, "https://parent.example.com");