比較 window.top 與 window.self:若相同說明為頂層視窗(直接訪問);若不同說明嵌入在 iframe/frame 中。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>測試 iframe 隱藏 div</title>
<script>
function adjustTopDiv() {
var topDiv = document.getElementById("top");
if (window.top === window.self) {
topDiv.style.display = 'block'; // 直接訪問:顯示
} else {
topDiv.style.display = 'none'; // 在 iframe 中:隱藏
}
}
</script>
</head>
<body onload="adjustTopDiv();">
<div id="top">
此區塊僅在直接訪問時顯示,iframe 嵌入時自動隱藏。
</div>
<p>頁面其他內容...</p>
</body>
</html>
X-Frame-Options: DENY 或 CSP frame-ancestors 更完整)。若 iframe 跨域,window.top 存取會拋出安全錯誤。需用 try-catch 包裹:
function isInIframe() {
try {
return window.top !== window.self;
} catch (e) {
return true; // 跨域無法存取 top,視為在 iframe 中
}
}
若僅為樣式調整,可考慮 CSS @media (display-mode: browser) 或容器查詢,但無法直接偵測 iframe 嵌套層級。