Open In App

How to detect the Internet connection is offline or not using JavaScript?

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Detecting if the internet connection is offline using JavaScript involves utilizing the navigator.onLine property. This property returns false when the browser is offline and true when connected, allowing you to respond to network connectivity changes in real-time.

Syntax:

function isOnline() { 
return ( navigator.onLine)
}

Example: In this example we hecks the browser’s online status using the navigator.onLine property. It updates the page with “Online” or “Offline” based on the connection status.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        detect the Internet connection is offline or not
    </title>
</head>

<body>

    <p>
        Click the button to check
        if the browser is online.
    </p>

    <button onclick="isOnline()">
        Click Me
    </button>

    <p id="demo"></p>

    <script>
        function isOnline() {

            if (navigator.onLine) {
                document.getElementById(
                    "demo").innerHTML = "Online";
            } else {
                document.getElementById(
                    "demo").innerHTML = "Offline";
            }
        }
    </script>

</body>

</html>

Output:

A-Check

Supported Browsers

The minimum version of browsers that supports the property:

  • Google Chrome: 14.0
  • Internet Explorer: Yes
  • Firefox: 3.5
  • Safari: 5.0.4
  • Opera: Yes


Next Article

Similar Reads