// 父頁面文檔上下文查找
$("#elementId", window.parent.document);
// 父頁面的父頁面
$("#elementId", window.parent.parent.document);
// 頂層窗口
$("#elementId", window.top.document);
// 打開當前窗口的窗口
$("#elementId", window.opener.document);
// 頂層窗口下的第 1 個 iframe
$("#elementId", window.top.frames[0].document);
// 指定 name 的 iframe
$("#elementId", window.frames["iframeName"].document);
window.parent.document.getElementById("elementId");
window.top.document.getElementById("elementId");
window.opener.document.getElementById("elementId");
window.top.frames[0].document.getElementById("elementId");
// 父頁面
const child = window.open('child.html', '_blank', 'width=600,height=400');
// 子頁面訪問父頁面
window.opener.document.getElementById('parentInput').value = 'from child';
window.opener.location.reload(); // 刷新父頁面
特點:雙向自由訪問(同源前提下),父頁面可通過 child.document 訪問子頁面。
// 父頁面
const result = window.showModalDialog('dialog.html', window, 'dialogWidth:400px;dialogHeight:300px;');
// 父頁面接收返回值
if (result !== undefined) { /* ... */ }
// 子頁面訪問父頁面
const parent = window.dialogArguments; // 接收父頁面傳入的第二個參數
parent.document.getElementById('age').value = 25;
// 子頁面返回值
window.returnValue = { name: 'John', age: 25 };
window.close();
⚠️ 已從 Web 標準移除,現代瀏覽器不支持,請勿在新項目使用。
類似 showModalDialog 但不阻塞父頁面,同樣已棄用。
// 父頁面
const child = window.open('child.html');
window.addEventListener('message', e => {
if (e.origin !== 'https://trusted-origin.com') return; // 安全驗證來源
if (e.data.type === 'FORM_SUBMIT') {
document.getElementById('result').textContent = e.data.payload;
}
});
// 子頁面
window.opener.postMessage({ type: 'FORM_SUBMIT', payload: '用戶提交的數據' }, 'https://parent-origin.com');
優點:跨域安全、解耦、不依賴同源策略、支持結構化數據傳遞。
<!-- 父頁面 -->
<iframe id="myFrame" src="child.html"></iframe>
<script>
const iframe = document.getElementById('myFrame');
iframe.onload = () => {
// 父 -> 子
iframe.contentWindow.postMessage({ action: 'init', data: 123 }, '*');
// 子 -> 父
window.addEventListener('message', e => {
if (e.source === iframe.contentWindow) {
console.log('收到子頁面消息:', e.data);
}
});
};
</script>
<!-- 子頁面 child.html -->
<script>
window.addEventListener('message', e => {
if (e.data.action === 'init') {
console.log('初始化數據:', e.data.data);
// 回傳
e.source.postMessage({ status: 'ready' }, e.origin);
}
});
</script>
e.origin 白名單。e.source 確認消息發送方身份。{ type, payload },避免任意代碼執行。