- Published on
Detect Internet Connection
One common challenge faced by developers is managing user interactions when internet connectivity fluctuates or is lost. JavaScript provides a way to let you make decisions based on user status (online/offline) through the navigator.onLine
property.
Detecting connectivity
Like mentioned, you can use navigator.onLine
to detect the user connectivity status. It returns a boolean value, where true means the user is online and false means offline.
if (navigator.onLine) {
// something happens
}
Detect status change
JavaScript also provides an event listener that is triggered when the connectivity status is changed.
window.addEventListener('online', something())
window.addEventListener('offline', something())
Example
Here's a simple example, where you get an console message on the user's status change.
document.addEventListener('online', () => {
console.log("You're connected to internet.")
})
document.addEventListener('offline', () => {
console.log('You have been disconnected.')
})
You can also have a button, which can tell you the connectivity status by clicking on it.
const statusBtn = document.querySelector('.status') // HTML button for status check
statusBtn.addEventListener('click', () => {
if (navigator.onLine) {
alert("You're online") // Returns true, connected
} else {
alert("You're offline") // Returns false, disconnected
}
})