萬盛學電腦網

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

JavaScript window.top 屬性深度解析:跨框架通訊的關鍵引用

定義

window.top 回傳 **視窗層級最頂層** 的 `Window` 物件參考。若目前視窗即為頂層,則 `top === window` (亦即 `top === self`)。

框架層級關係圖


// 頂層頁面 (top.html)
window.top === window.self  // true
window.top === window.parent // true

// 子框架 (child.html) - 直接嵌在 top.html
window.top === window.parent // true (父即頂層)
window.top !== window.self   // true

// 孫框架 (grandchild.html) - 嵌在 child.html
window.top === window.parent.parent // true
window.top !== window.parent        // true
window.top !== window.self          // true

核心屬性對照表

屬性指向同源可存取跨域可存取
window.self / window當前視窗✅ 完整✅ 完整
window.parent父視窗 (若無則指向 self)✅ 完整❌ SecurityError
window.top頂層視窗✅ 完整❌ SecurityError
window.frames子框架集合 (類陣列)✅ 完整❌ 僅能取得 length
iframe.contentWindow特定 iframe 的 window✅ 完整❌ SecurityError

實戰應用場景

1. 子框架跳出框架導航頂層頁面

// 子框架內
$('#logoutBtn').click(function() {
    top.location.href = '/login'; // 強制頂層跳轉,防止釣魚網站嵌入
});

2. 頂層頁面向所有子框架廣播訊息

// 頂層頁面
function broadcastToFrames(message) {
    for (var i = 0; i < frames.length; i++) {
        try {
            frames[i].postMessage(message, '*'); // 生產環境指定 origin
        } catch (err) {
            console.warn('跨域框架無法發送:', err);
        }
    }
}

// 子框架監聽
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://trusted-parent.com') return;
    if (e.data.type === 'LOGOUT') handleLogout();
});

3. 判斷是否在 iframe 中嵌套

function isInIframe() {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true; // 跨域存取 top 拋錯,視為在 iframe 中
    }
}

// 用途:禁止被嵌入 (防點擊劫持)
if (isInIframe()) {
    top.location = self.location; // 破框
    // 或 HTTP Header: X-Frame-Options: DENY / SAMEORIGIN
}

4. 取得頂層頁面共享資料/工具函式

// 頂層頁面定義
window.App = {
    config: { apiBase: '/api/v1', user: { id: 1, role: 'admin' } },
    utils: { formatDate: ..., http: ... }
};

// 子框架使用 (同源)
var config = top.App.config;
var http = top.App.utils.http;
http.get(config.apiBase + '/user/profile');

跨域限制與解決方案

  • 無法直接存取跨域 top:讀取屬性即拋 SecurityError。
  • 解決:`postMessage` 雙向通訊、代理 iframe (同域中介)、CORS + `sandbox="allow-same-origin allow-scripts"`。

現代替代方案

  • ES Modules 動態 import:共享程式碼而非共享全域 `top` 物件。
  • SharedWorker:多視窗/框架共享單一 Worker 實例、狀態同步。
  • BroadcastChannel API:同源不同視窗/框架/分頁廣播訊息。

安全警示

濫用 `top` 存取會造成強耦合、難以測試、XSS 風險擴大。**原則:子框架盡量無感知父層,透過明確定義的介面 (postMessage/props) 通訊。**

copyright © 萬盛學電腦網 all rights reserved