萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

iframe 控制父頁面局部刷新:從子頁面重載父容器 iframe 的實作模式

應用場景

  • 父頁面 a.jsp 嵌入 <iframe id="frame" src="b.jsp">。
  • 子頁面 b.jsp 完成操作(如新增、刪除)後,需觸發父頁面的 iframe 重新載入,呈現最新資料,且不刷新整個父頁面。

實作思路

子頁面透過 window.parent 存取父頁面 DOM,找到對應 iframe 元素,重新設定其 src 屬性(即使值相同)即可觸發重載。

代碼實作

子頁面 b.jsp

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 會重新請求文件、解析、渲染。若頻繁操作,考慮改用 AJAX 取得資料後局部更新 DOM,或使用前端框架狀態管理。
  • 歷史記錄: iframe.src = ... 會在 iframe 歷史堆疊新增記錄,使用者點「上一頁」會回到 iframe 上一狀態而非父頁面。若不希望記錄歷史,可用 iframe.contentWindow.location.replace(newSrc)。

跨域場景:postMessage 方案

// 子頁面
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);
  }
});
copyright © 萬盛學電腦網 all rights reserved