萬盛學電腦網

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

JavaScript 框架/iframe 跨頁面刷新與通信完整大全

框架(frameset/iframe)雖已淡出主流布局,但在老系統、嵌入式儀表盤、第三方組件嵌入等場景仍廣泛存在。本文系統整理**父頁面↔子頁面、同級 iframe 間**的刷新、跳轉、數據傳遞方法,並給出現代 postMessage 跨域通信方案。

同域環境下的框架引用鏈

// 父頁面訪問子 iframe
window.frames["iframeName"]           // 通過 name
window.frames[0]                      // 通過索引
document.getElementById("iframeId").contentWindow // 標準 DOM API (推薦)
iframeElement.contentDocument         // 直接獲取 document (IE8+)

// 子頁面訪問父頁面
window.parent                         // 直接父級
window.top                            // 頂層窗口

// 同級 iframe 互訪
window.parent.frames["brotherName"]
window.parent.document.getElementById("brotherId").contentWindow

七種刷新子頁面寫法(功能等價,擇一即可)

// 假設父頁面中有一個 name="bottom" 的 iframe
// 1. 索引
window.parent.frames[1].location.reload();
// 2. name 屬性訪問
window.parent.frames.bottom.location.reload();
// 3. 字符串索引
window.parent.frames["bottom"].location.reload();
// 4. item 方法
window.parent.frames.item(1).location.reload();
window.parent.frames.item('bottom').location.reload();
// 5. 直接屬性訪問 (name 映射為 window 屬性)
window.parent.bottom.location.reload();
// 6. 方括號屬性訪問
window.parent['bottom'].location.reload();

刷新當前頁面的 8 種方法

history.go(0)
location.reload()
location = location
location.assign(location)
document.execCommand('Refresh') // 仅 IE
window.navigate(location)       // 仅 IE
location.replace(location)      // 無歷史記錄
document.URL = location.href

自動刷新/跳轉 Meta 標籤與 JS 定時器

<!-- 20 秒自動刷新 -->
<meta http-equiv="refresh" content="20">

<!-- 20 秒後跳轉 -->
<meta http-equiv="refresh" content="20;url=https://example.com">

<!-- JS 版定時刷新 -->
<script>
setInterval(function(){ window.location.reload(); }, 1000); // 1秒
</script>

ASP.NET 服務端輸出刷新父頁腳本

// 1. 刷新 opener (彈窗場景)
this.Response.Write("<script>opener.location.reload();</script>");
// 2. 刷新父框架
this.Response.Write("<script>parent.location.reload();</script>");
// 3. 指定 URL 刷新
this.Response.Write("<script>opener.location.href='target.aspx';</script>");

跨域場景:postMessage 安全通信 (現代標準)

// 父頁面
var iframe = document.getElementById('myIframe');
iframe.onload = function() {
    // 發送消息到子頁面 (指定目標源 *)
    iframe.contentWindow.postMessage({type: 'REFRESH', data: {id: 123}}, '*');
};

// 接收子頁面回傳
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://trusted-child.com') return; // 驗證源
    if (e.data.type === 'READY') { /* ... */ }
});

// 子頁面
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://trusted-parent.com') return;
    if (e.data.type === 'REFRESH') {
        location.reload(); // 或局部更新數據
        // 回確認
        e.source.postMessage({type: 'READY'}, e.origin);
    }
});

iframe 自適應高度(同域)

// 父頁面定時檢測
setInterval(function() {
    var iframe = document.getElementById('myIframe');
    try {
        var h = iframe.contentWindow.document.body.scrollHeight;
        iframe.style.height = h + 'px';
    } catch(e) { /* 跨域無權訪問 */ }
}, 200);

// 更優雅:子頁面主動通報
// 子頁面: parent.postMessage({type:'resize', height: document.body.scrollHeight}, '*');
// 父頁面: 監聽 message 類型 resize 設置高度

總結建議

  • **新專案避免 frameset/iframe 布局**,採用 SPA 路由或微前端(qiankun、single-spa、Module Federation)。
  • 必須使用 iframe 時:**同域優先**,盡量同主域配置 document.domain(已棄用但仍可用)或反向代理統一源。
  • **跨域必須用 postMessage**,嚴格驗證 e.origin,勿使用 *。
  • 刷新/跳轉優先用 location.reload() / location.href = ...,語義清晰兼容性佳。
copyright © 萬盛學電腦網 all rights reserved