Thuộc tính window.self trả về tham chiếu đến cửa sổ hiện tại (chính nó). Dùng để so sánh với window.top kiểm tra xem cửa sổ có phải top-level hay đang trong iframe.
Cú pháp
window.self
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat; text-align: center; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 50%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.show { font-size: 1.2rem; margin-top: 1rem; }
</style>
<body>
<h1>Demo window.self</h1>
<button onclick="checkTop()" class="btn">Kiểm tra có phải cửa sổ cha nhất không?</button>
<div class="show"></div>
<script>
function checkTop() {
var msg = window.top === window.self
? '✅ Cửa sổ này LÀ cửa sổ cha nhất (top-level)'
: '⚠️ Cửa sổ này NẰM TRONG iframe (không phải top)';
document.querySelector('.show').innerHTML = msg;
}
</script>
</body>
</html>
Kết quả
Mở file trực tiếp → "LÀ cửa sổ cha nhất". Nhúng file vào <iframe> của trang khác → "NẰM TRONG iframe".
Ứng dụng: Frame busting (ngăn nhúng iframe), điều chỉnh UI khi nhúng, bảo mật clickjacking. window.self === window.top = true nếu không trong iframe.