萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 刷新 iframe 頁面的多種方法與最佳實踐

方法一:原生 location.reload()


// 強制從伺服器重新載入 (相當於 F5)
window.location.reload(true);

// 僅從快取載入 (預設)
window.location.reload(false);
// 或
window.location.reload();

方法二:指定 iframe 重新載入

原生 JS

// 方式 1:contentWindow.location.reload() (推薦)
document.getElementById('myframe').contentWindow.location.reload(true);

// 方式 2:重新設定 src (會觸發 onload)
document.getElementById('myframe').src = document.getElementById('myframe').src;

// 方式 3:contentDocument.location.reload() (較少用)
document.getElementById('myframe').contentDocument.location.reload(true);

jQuery 封裝

// 方式 1:attr 重設 src (觸發重載)
$('#myframe').attr('src', $('#myframe').attr('src'));

// 方式 2:呼叫原生 reload
$('#myframe')[0].contentWindow.location.reload(true);

// 封裝函式
function refreshIframe(iframeSelector) {
    var $iframe = $(iframeSelector);
    if ($iframe.length) {
        $iframe[0].contentWindow.location.reload(true);
    }
}

// 使用
refreshIframe('#myframe');

完整可執行範例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery 刷新 iframe 示範</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <iframe id="myframe" width="100%" height="400" frameborder="0" src="test.html"></iframe>
    <br><br>
    <button onclick="refreshFrame1()">方法1: contentWindow.reload()</button>
    <button onclick="refreshFrame2()">方法2: jQuery attr src 重設</button>
    <button onclick="refreshFrame3()">方法3: 原生 src 重設</button>
    
    <script>
        function refreshFrame1() {
            document.getElementById('myframe').contentWindow.location.reload(true);
        }
        function refreshFrame2() {
            $('#myframe').attr('src', $('#myframe').attr('src'));
        }
        function refreshFrame3() {
            var iframe = document.getElementById('myframe');
            iframe.src = iframe.src;
        }
    </script>
</body>
</html>

特殊場景:刷新父視窗、同級 iframe、opener 視窗

場景代碼說明
iframe 刷新父視窗parent.location.reload();子頁面呼叫
子視窗刷新開啟它的視窗self.opener.location.reload();window.open 開啟的彈窗
刷新同層級另一個 iframeparent.otherFrameName.location.reload();需知道目標 iframe name
刷新頂層視窗top.location.reload();穿透多層 iframe

常見問題與解決

1. document.frames['name'] 不可用

舊代碼常見 document.frames('ifrmname').location.reload(),**現代瀏覽器已不支援**。請改用 window.frames['name'] 或 document.getElementById('id').contentWindow。

2. 跨域 iframe 無法呼叫 reload()

不同源的 iframe 無法存取 contentWindow。解決方案:

// 父視窗:重新設定 src (跨域也可操作)
$('#crossDomainIframe').attr('src', function(i, val) {
    return val + (val.indexOf('?') > -1 ? '&' : '?') + '_t=' + Date.now();
});

// 子視窗:postMessage 通知父視窗重載
window.parent.postMessage({action: 'reloadIframe', id: 'myframe'}, '*');

3. 刷新後捲動位置重置

// 保存捲動位置
var scrollTop = $('#myframe')[0].contentWindow.document.documentElement.scrollTop;

// 重載後恢復 (需在 iframe 內部頁面執行)
$(window).on('load', function() {
    if (sessionStorage.scrollTop) {
        document.documentElement.scrollTop = sessionStorage.scrollTop;
        sessionStorage.removeItem('scrollTop');
    }
});

現代替代方案:避免完整重載

  • AJAX 局部更新:$('#container').load('/api/content')
  • WebSocket / SSE:伺服器推送更新
  • 框架路由:Vue Router / React Router 切換元件,無需 iframe
  • iframe.srcdoc:直接設定 HTML 內容(同源)

總結建議

需求推薦方法
同源 iframe 完整重載iframe.contentWindow.location.reload(true)
跨域 iframe 強制重載重設 src 加時間戳參數
無感局部更新AJAX / Fetch + DOM 更新
保持捲動位置sessionStorage 暫存 + onload 恢復

核心原則:能用 AJAX 局部更新就不要重載 iframe;必須重載時,同源用 reload(true),跨域用 src 重設。

copyright © 萬盛學電腦網 all rights reserved