Home >Web Front-end >JS Tutorial >How Can I Detect Offline Internet Connection Status in JavaScript?
How to Determine if the Internet Connection is Offline in JavaScript
Detecting internet connectivity in JavaScript is a crucial aspect of ensuring a seamless user experience for web applications. There are various approaches to achieve this, but one of the most effective methods involves utilizing the window.navigator.onLine property.
The window.navigator.onLine property indicates whether the device has an active internet connection. Its value is a boolean, where true represents an online connection and false represents an offline connection. To determine the current network status, simply access this property.
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
Additionally, you can subscribe to the online and offline events to be notified whenever the network status changes.
window.addEventListener('online', () => console.log('Became online')); window.addEventListener('offline', () => console.log('Became offline'));
To manually check the current network status on demand, you can create a button that triggers the evaluation of the window.navigator.onLine property.
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
The above is the detailed content of How Can I Detect Offline Internet Connection Status in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!