Prop Nav Online
## JavaScript Navigator onLine Property
The `navigator.onLine` property is a read-only property of the `Navigator` object. It allows developers to detect whether the user's browser is currently connected to the network (online) or disconnected (offline).
---
## Definition and Usage
* The `navigator.onLine` property returns a boolean value indicating the online status of the browser.
* It returns `true` if the browser is online, and `false` if the browser is offline.
* This property is **read-only**.
---
## Syntax
```javascript
let isOnline = navigator.onLine;
```
### Return Value
| Return Type | Description |
| :--- | :--- |
| `Boolean` | Returns `true` if the browser is connected to a network, otherwise returns `false`. |
---
## Browser Support
The `navigator.onLine` property is fully supported by all major modern web browsers:
| Chrome | Internet Explorer / Edge | Firefox | Safari | Opera |
| :---: | :---: | :---: | :---: | :---: |
| Yes | Yes | Yes | Yes | Yes |
---
## Code Examples
### Example 1: Basic Usage
Check the current network status when the page loads:
```javascript
// Get the current online status
let onlineStatus = navigator.onLine;
if (onlineStatus) {
console.log("The browser is online.");
} else {
console.log("The browser is offline.");
}
```
### Example 2: Real-time Network Status Monitoring
Because network conditions can change dynamically, you should combine `navigator.onLine` with the `online` and `offline` window event listeners to monitor connectivity changes in real-time.
```javascript
function updateOnlineStatus(event) {
if (navigator.onLine) {
console.log("Network connection restored.");
// Perform actions like syncing local data with the server
} else {
console.log("Network connection lost.");
// Perform actions like saving user input locally or showing an offline banner
}
}
// Listen for online and offline events
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
```
---
## Important Considerations
While `navigator.onLine` is widely supported, developers should keep the following behaviors in mind:
1. **False Positives:**
The property returns `true` if the browser is connected to a local network (LAN) or a router, even if that router does not have actual access to the internet. Therefore, `true` only guarantees that a network adapter is active, not necessarily that the internet is reachable.
2. **Reliability Check:**
To guarantee actual internet connectivity, it is recommended to perform a lightweight fetch request (e.g., a `HEAD` request to a reliable endpoint) when `navigator.onLine` returns `true`.
3. **Virtualization and Emulators:**
In some virtualization environments or older browsers, the behavior of this property might vary depending on how the operating system reports network interface states.
YouTip