Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính window.top trong HTML

Thuộc tính window.top trả về tham chiếu đến cửa sổ cha nhất (top-level) trong hệ phân cấp frame/iframe.

Cú pháp

window.top

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: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
  .show { font-size: 1.2rem; margin-top: 1rem; }
</style>
<body>
<h1>Demo window.top</h1>
<button onclick="checkTop()" class="btn">Kiểm tra cửa sổ cha nhất</button>
<div class="show"></div>
<script>
  function checkTop() {
    var msg = window.top === window.self 
      ? '✅ Đây là cửa sổ cha nhất (top-level window)' 
      : '⚠️ Đây là iframe con, cửa sổ cha là: ' + window.top.location.href;
    document.querySelector('.show').innerHTML = msg;
  }
</script>
</body>
</html>

Kết quả

Mở trực tiếp → "là cửa sổ cha nhất". Trong iframe → hiển thị URL của trang cha.

Lưu ý: Cross-origin iframe sẽ bị chặn truy cập window.top.location (SecurityError). Dùng try-catch hoặc window.self !== window.top chỉ boolean.