Navigator: onLine property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheonLine property of theNavigator interface returns whether the device is connected to the network, withtrue meaning online andfalse meaning offline. The property's value changes after the browser checks its network connection, usually when the user follows links or when a script requests a remote page. For example, the property should returnfalse when users click links soon after they lose internet connection. When its value changes, anonline oroffline event is fired on thewindow.
Browsers and operating systems leverage different heuristics to determine whether the device is online. In general, connection to LAN is considered online, even though the LAN may not have Internet access. For example, the computer may be running a virtualization software that has virtual ethernet adapters that are always "connected". On Windows, the online status is determined by whether it can reach a Microsoft home server, which may be blocked by firewalls or VPNs, even if the computer has Internet access. Therefore, this property is inherently unreliable, and you should not disable features based on the online status, only provide hints when the user may seem offline.
In this article
Value
A boolean.
Examples
>Basic usage
To check if you are online, querywindow.navigator.onLine, as in thefollowing example:
if (navigator.onLine) { console.log("online");} else { console.log("offline");}If the browser doesn't supportnavigator.onLine the above example willalways come out asfalse/undefined.
Listening for changes in network status
To see changes in the network state, useaddEventListener tolisten for the events onwindow.online andwindow.offline, asin the following example:
window.addEventListener("offline", (e) => { console.log("offline");});window.addEventListener("online", (e) => { console.log("online");});Specifications
| Specification |
|---|
| HTML> # dom-navigator-online-dev> |