Home > Web Front-end > JS Tutorial > How Can I Detect Offline Internet Connection Status in JavaScript?

How Can I Detect Offline Internet Connection Status in JavaScript?

Mary-Kate Olsen
Release: 2024-12-06 03:33:12
Original
645 people have browsed it

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');
Copy after login

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'));
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template