a.jsp 嵌入 <iframe id="frame" src="b.jsp">。b.jsp 完成操作(如新增、刪除)後,需觸發父頁面的 iframe 重新載入,呈現最新資料,且不刷新整個父頁面。子頁面透過 window.parent 存取父頁面 DOM,找到對應 iframe 元素,重新設定其 src 屬性(即使值相同)即可觸發重載。
function refreshParentIframe() {
// 1. 取得父頁面的 iframe 元素
const iframe = window.parent.document.getElementById('frame');
if (!iframe) {
console.error('找不到父頁面 iframe#frame');
return;
}
// 2. 取得當前 src
const currentSrc = iframe.getAttribute('src');
// 3. 重新設定 src 觸發重載
// 技巧:加上時間戳避免瀏覽器快取
iframe.setAttribute('src', currentSrc + (currentSrc.includes('?') ? '&' : '?') + '_t=' + Date.now());
}
// 操作完成後呼叫
refreshParentIframe();
// 父頁面預先暴露刷新函式(更優雅,降低耦合)
// a.jsp 中
window.refreshChildFrame = function(frameId) {
const iframe = document.getElementById(frameId);
if (iframe) {
const src = iframe.src;
iframe.src = src + (src.includes('?') ? '&' : '?') + '_t=' + Date.now();
}
};
// 子頁面呼叫
window.parent.refreshChildFrame('frame');
window.parent.document 存取被瀏覽器阻擋(跨域錯誤)。跨域需用 postMessage 通訊。src 可能不觸發重載(瀏覽器快取),建議附加查詢字串時間戳或隨機數。iframe.src = ... 會在 iframe 歷史堆疊新增記錄,使用者點「上一頁」會回到 iframe 上一狀態而非父頁面。若不希望記錄歷史,可用 iframe.contentWindow.location.replace(newSrc)。// 子頁面
window.parent.postMessage({ type: 'REFRESH_IFRAME', frameId: 'frame' }, 'https://parent-domain.com');
// 父頁面
window.addEventListener('message', (e) => {
if (e.origin !== 'https://child-domain.com') return;
if (e.data.type === 'REFRESH_IFRAME') {
window.refreshChildFrame(e.data.frameId);
}
});