框架(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();
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
<!-- 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>
// 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>");
// 父頁面
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);
}
});
// 父頁面定時檢測
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 設置高度
document.domain(已棄用但仍可用)或反向代理統一源。postMessage**,嚴格驗證 e.origin,勿使用 *。location.reload() / location.href = ...,語義清晰兼容性佳。