Home >Web Front-end >JS Tutorial >How Can JavaScript Detect and Respond to Internet Connectivity Changes?
Detecting Internet Connectivity in JavaScript: A Comprehensive Guide
In today's web development landscape, ensuring a robust and reliable user experience often hinges on detecting whether the internet connection is offline or active. Fortunately, JavaScript offers several methods to achieve this critical functionality.
Introducing the window.navigator.onLine Property
Most major browsers now support the window.navigator.onLine property, a Boolean value that indicates the current state of the internet connection. Access this property to check whether the user is connected to the internet.
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
Listening for Connectivity Events
Browsers also provide event listeners for the online and offline events, which trigger when the connectivity status changes. By listening to these events, you can respond to changes in real-time.
window.addEventListener('online', () => console.log('Became online')); window.addEventListener('offline', () => console.log('Became offline'));
Verifying the Connectivity Status with a Click
To demonstrate these methods in action, create an HTML button that, when clicked, checks and displays the current window.navigator.onLine value:
<button>
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
Additional Considerations
The above is the detailed content of How Can JavaScript Detect and Respond to Internet Connectivity Changes?. For more information, please follow other related articles on the PHP Chinese website!