Online and Offline Events in JavaScript

Vaibhav Sharma
3 min readJun 5, 2019

In the web applications, sometimes a user will be disconnected from the network. At this time how the application will perform. So, if you create a good app, so it is must detect when the user goes offline and behave accordingly. In some of my freelance project, I was facing this type of problem. After that, I referred HTML5 MDN for working with offline and online events.

For creating a good application, you must know when the user goes offline and write logic accordingly. There is some use-case when detecting offline and online events are important.

Use-case 1 :

When a user is filling a long form and middle of filling the form, the user goes offline due to a power cut or some problem of connectivity. In this use-case detect an offline event and save data in local storage and when user will again be connected with the network, data will send to the server.

Use-case 2:

The second use-case is related to app-cache. When the user goes offline, then loaded content from app-cache.

Offline / Online Event Detection :

For detecting the offline and online events, the navigator object will help you. By the use of below code, you can detect, the user is online or offline.

navigator.onLine;

Above code will give you boolean value true or false. If the user is online then above code give you true otherwise false.

if(navigator.onLine === true){
console.log('online')
}else{
console.log('offline')
}

If a user is online, the first console will be printed otherwise the second console will be printed. But this code of snippet only checks if the user is online or offline. But in some scenario, we fire the function, when the user goes offline or connected with the network again. For this requirement, we can use window.addEventListner.

window.addEventListener('online', () => {
console.log('online')
})
window.addEventListener('offline', () => {
console.log('offline')
})
Detect online and offline events

Use-case :

When the user goes offline, save data in local storage and when the user will come back in the network get data from local storage and send to server and clear the local storage.

function updateOnlineStatus(event){
if(event.type == 'offline') {
console.log('offline')
localStorage.setItem('user', 'Vaibhav Sharma');
}

if(event.type == 'online') {
console.log(localStorage.getItem('user'));
localStorage.clear();
}
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

Elaboration of code:

  1. Create a function which gives to window.addEventListener, when user goes offline or come back in network.
  2. This function checks the type of event.
  3. If type of event is ‘offline’, then save data in local storage.
  4. If type of event is ‘online’, then fetch data from local storage and clear the local storage.

--

--