How can you check if you are online in a Progressive Web Application

266 Views Asked by At

I am developing a Progressive Web Application and I am trying to make sure that end users can access and edit their information locally while offline and then sync it with the database once coming back online. I know its possible I just cannot seem to find the resources that point me to how to do this. I want to check to see if the user is online -> yes then use my api to authenticate/authorize them to access application content
-> no then set a disclaimer that if they have not logged into this device previously while online and selected for the device to remember them then they will not be able to access the application content. But if they have then they can log in.

Just checking if they are online is the part that I am struggling with at the moment.

I have tried using a ping to discover that browsers do not support a ping. I also tried using the navigator.onLine as shown in the link below: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#basic_usage

I thought about looking into if a await method times out, but I am still pretty new, and I couldn't find anything that explained if I could do that and how.

Any help with this would be greatly appreciated.

1

There are 1 best solutions below

0
On

You can use thease 3 methods:

console.log(navigator.onLine); // Returns a Boolean  


// This event is called when the internet is connected:

window.addEventListener('online', ()=>{
  console.log('onlined...');
})


// This event is called when the internet is disconnected:

window.addEventListener('offline', ()=>{
  console.log('offlined...');
})