// 子視窗/iframe 中取得父視窗元素
$('#parentElementId', window.parent.document);
// 等同原生
window.parent.document.getElementById('parentElementId');
// 父視窗的父視窗(祖父視窗)
$(selector, window.parent.parent.document);
// iframe 父視窗
$(selector, window.parent.document);
// window.open 開啟的子視窗取得開啟者
$(selector, window.opener.document);
// showModalDialog 開啟的對話框取得調用者
$(selector, window.dialogArguments.document);
window.parent.location.reload();parent.subWindow_add.Close();(需父視窗定義對應方法)parent.$('#4thEditTable').load(window.parent.location.href + ' #4thEditTable');
利用 jQuery .load(url fragment) 僅載入片段,實現無感局部更新。
iframe.onload 後或父視窗 ready 後操作,否則元素尚未就緒。使用 postMessage 跨文檔通訊,安全、支援跨域:
// 子視窗發送
window.parent.postMessage({ type: 'refresh', data: {} }, 'https://parent-domain.com');
// 父視窗接收
window.addEventListener('message', e => {
if (e.origin !== 'https://child-domain.com') return;
if (e.data.type === 'refresh') $('#list').load('/api/list #list');
});