Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML window.top 속성 – 현재 창이 최상위 브라우저 창인지 확인하는 방법

HTML의 window.top 속성은 현재 창이 속한 브라우저 창 계층 구조에서 가장 상위에 있는(최상위) 창 객체를 반환합니다. 특히 iframe이나 프레임 구조로 페이지가 중첩되어 있을 때, 현재 창이 최상위 창인지 아닌지를 판별하는 데 매우 유용하게 활용됩니다.

문법(Syntax)

window.top 속성의 기본 문법은 다음과 같습니다.

window.top

이 속성은 읽기 전용(read-only)이며, 별도의 매개변수 없이 호출하면 해당 창 계층에서 가장 위에 있는 Window 객체를 반환합니다. 일반적으로 window.self(현재 창 자신)와 비교하여 현재 문서가 최상위 컨텍스트에서 실행 중인지 확인하는 용도로 많이 사용됩니다.

예제(Example)

다음 예제는 버튼을 클릭하면 window.topwindow.self를 비교하여, 현재 창이 최상위 창인지 여부를 화면에 표시합니다.

<!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: 30%;
        display: block;
        color: #fff;
        outline: none;
        cursor: pointer;
        margin: 1rem auto;
    }
    .show{
        font-size:1.2rem;
    }
</style>
<body>
<h1>HTML Window top Property Demo</h1>
<button onclick="create()" class="btn">Check current window is topmost</button>
<div class="show"></div>
<script>
    function create(){
        if(window.top === window.self){
            document.querySelector('.show').innerHTML='The current window is the topmost window';
        } else{
            document.querySelector('.show').innerHTML='The current window is not the topmost window';
        }
    }
</script>
</body>
</html>

실행 결과(Output)

HTML window.top 속성 – 현재 창이 최상위 브라우저 창인지 확인하는 방법

위 코드를 실행하면 그라디언트 배경 화면에 “Check current window is topmost” 버튼이 나타납니다. 이 버튼을 클릭하면 현재 창이 최상위 창인지 여부가 검사되어 결과가 표시됩니다.

HTML window.top 속성 – 현재 창이 최상위 브라우저 창인지 확인하는 방법

페이지가 iframe 등으로 중첩되어 있지 않은 일반적인 환경이라면 “The current window is the topmost window”(현재 창은 최상위 창입니다)라는 메시지가 출력됩니다. 반대로 iframe 내부에서 실행된다면 두 객체가 다르므로 “not the topmost window”라는 결과가 반환됩니다.