Monitoring Internet Connectivity Status in JavaScript
Detecting offline internet connections is crucial for web applications that require consistent network access. In JavaScript, the window.navigator.onLine property and its associated online and offline events provide a convenient way to monitor connectivity status.
Detecting Offline Status:
To detect offline status, you can access the window.navigator.onLine property, which returns a boolean value indicating whether the user is connected to the internet.
window.addEventListener:
You can also use window.addEventListener to listen for the online and offline events. When the connectivity changes from online to offline, the offline event triggers, and vice versa.
Code Example:
The following code snippet demonstrates how to use these methods:
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line'); window.addEventListener('online', () => console.log('Became online')); window.addEventListener('offline', () => console.log('Became offline')); document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
This code logs the initial connectivity status, listens for changes, and allows you to manually check the status by clicking a button.
Note:
The availability of these methods may vary depending on the browser and platform.
The above is the detailed content of How Can JavaScript Detect and Monitor Internet Connectivity Status?. For more information, please follow other related articles on the PHP Chinese website!