Blog>
Snippets

Offline Event Detection and User Notification

Implement a feature that detects when the application goes offline and notify users, updating the UI to reflect the offline state.
/* Event listener for detecting offline status */
window.addEventListener('offline', function(event) {
    notifyUserOffline();
});
Adds an event listener to the window object that listens for the 'offline' event, which is automatically triggered by the browser when it detects that the network connection has been lost. When this event occurs, the notifyUserOffline function is called.
/* Event listener for detecting online status */
window.addEventListener('online', function(event) {
    notifyUserOnline();
});
Adds an event listener to the window object that listens for the 'online' event, which is automatically triggered by the browser when it detects that the network connection has been restored. When this event occurs, the notifyUserOnline function is called.
/* Function to update UI and notify user of the offline status */
function notifyUserOffline() {
    // Update the UI to indicate that the application is offline
    document.body.classList.add('offline');
    // Display an offline notification to the user
    alert('You are now offline. Some features may not be available.');
}
Defines a function called notifyUserOffline that updates the user interface to reflect the offline status by adding a class to the body element, which could be used to change the appearance to indicate the offline state. It also shows an alert to inform the user that they have gone offline.
/* Function to update UI and notify user of the online status */
function notifyUserOnline() {
    // Update the UI to indicate that the application is online
    document.body.classList.remove('offline');
    // Display an online notification to the user
    alert('You are back online.');
}
Defines a function called notifyUserOnline that updates the user interface to reflect the online status by removing the 'offline' class from the body element. It also shows an alert to inform the user that the connection has been restored and they are back online.