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 |
// 子框架內
$('#logoutBtn').click(function() {
top.location.href = '/login'; // 強制頂層跳轉,防止釣魚網站嵌入
});
// 頂層頁面
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();
});
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
}
// 頂層頁面定義
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。濫用 `top` 存取會造成強耦合、難以測試、XSS 風險擴大。**原則:子框架盡量無感知父層,透過明確定義的介面 (postMessage/props) 通訊。**