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

HTML navigator onLine 속성 – 브라우저 온라인/오프라인 상태 확인하기

HTML의 navigator.onLine 속성은 현재 브라우저가 온라인 상태인지 아니면 오프라인 상태인지를 나타내는 불리언(Boolean) 값을 반환합니다. 이 속성은 네트워크 연결 여부에 따라 다른 동작을 수행해야 하는 웹 애플리케이션에서 매우 유용하게 활용됩니다.

문법(Syntax)

navigator.onLine 속성의 기본 문법은 다음과 같습니다.

navigator.onLine

이 속성은 별도의 매개변수 없이 호출하며, 인터넷에 연결되어 있으면 true, 연결되어 있지 않으면 false를 반환합니다.

예제(Example)

HTML navigator onLine 속성을 활용한 예제 코드를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<style>
    body {
        color: #000;
        height: 100vh;
        background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
        text-align: center;
    }
    .btn {
        background: #db133a;
        border: none;
        height: 2rem;
        border-radius: 20px;
        width: 330px;
        display: block;
        color: #fff;
        outline: none;
        cursor: pointer;
        margin: 1rem auto;
    }
    .show {
        font-size: 1.2rem;
        color: #fff;
    }
</style>
<body>
<h1>HTML navigator onLine property Demo</h1>
<button class="btn" onclick="display()">Check Browser Online/Offline Mode</button>
<div class="show"></div>
<script>
    function display() {
        var msg = document.querySelector(".show");
        if (navigator.onLine) {
            msg.innerHTML = "Hey! You are online";
        } else {
            msg.innerHTML = "Hey! You are offline";
        }
    }
</script>
</body>
</html>

실행 결과(Output)

HTML navigator onLine 속성 – 브라우저 온라인/오프라인 상태 확인하기

위 예제를 실행한 후 “Check Browser Online/Offline Mode” 버튼을 클릭하면 현재 브라우저가 온라인 모드인지 오프라인 모드인지 확인할 수 있습니다.

HTML navigator onLine 속성 – 브라우저 온라인/오프라인 상태 확인하기

네트워크가 정상적으로 연결된 상태에서 버튼을 클릭하면 “Hey! You are online”이라는 메시지가 화면에 표시됩니다.

이번에는 네트워크 연결을 의도적으로 끊은 후 다시 “Check Browser Online/Offline Mode” 버튼을 클릭해 보세요.

HTML navigator onLine 속성 – 브라우저 온라인/오프라인 상태 확인하기

네트워크가 차단된 상태에서는 “Hey! You are offline”이라는 메시지가 출력되며, 이를 통해 navigator.onLine 속성이 브라우저의 연결 상태를 정확하게 감지하는 것을 확인할 수 있습니다.