在開發嵌入式元件、廣告 SDK 或需防止點擊劫持的場景時,準確偵測頁面是否身處 <iframe> 或 <frame> 中至關重要。本文整理各種偵測技巧、瀏覽器差異與最佳實踐。
window.top !== window.self最常見的判斷方式,比較當前視窗與最頂層視窗是否為同一參考。
if (window.top !== window.self) {
console.log('頁面在框架內');
}
缺點:無法區分 iframe 與 frame;同源策略限制下,跨域框架會拋出錯誤導致腳本中斷。
window.frameElementframeElement 回傳嵌入當前頁面的元素(iframe 或 frame),若為頂層頁面則為 null。
if (window.frameElement) {
console.log('頁面在框架內,框架標籤:', window.frameElement.tagName); // "IFRAME" 或 "FRAME"
}
此屬性在同源情況下完美運作;跨域時同樣受同源策略限制,存取會拋出 SecurityError。
結合 try...catch 避免跨域錯誤中斷腳本:
function isInFrame() {
try {
return window.top !== window.self;
} catch (e) {
// 跨域無法存取 top,但確定在框架內
return true;
}
}
function getFrameType() {
try {
if (window.frameElement) {
return window.frameElement.tagName.toLowerCase(); // "iframe" 或 "frame"
}
} catch (e) {
// 跨域無法存取 frameElement
}
return null;
}
舊版 IE (IE8 及以下) 在某些情況下 top !== self 判斷失效,且 frameElement 可能回傳錯誤類型。現代專案若無需支援 IE 可忽略;若必須支援,建議採用 window.parent !== window 搭配 frameElement 雙重檢查。
if (isInFrame()) {
// 強制跳出框架
if (window.top !== window.self) {
window.top.location = window.self.location;
}
}
window.frameElement 取得框架類型try...catchwindow.top !== window.self 配合 catch 最穩健window.parent 行為掌握這些技巧,能讓您的前端程式在嵌入式環境中更安全、更可控。