2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
Alrampaz
  • 21
  • 2
  • So what happened with the navigator.online method? Seems like that's the simplest way. [A detailed usage](https://stackoverflow.com/a/71921156) – RBee Jul 27 '23 at 20:12
  • when I tried to use it and Idk if there was a difference in setup but VS was wanting me to download different NuGet packages and I had tried each of them, deleting the previous one after each attempt, and after the install the rest of the command would error out, and say that, that package didn't have the next function. So I missed something or I don't have the right package installed and I didn't read in that article of a specific package that needs to be installed to use those functions. – Alrampaz Jul 28 '23 at 18:11
  • Follow the answer instructions I linked, you don't need any extra packages. – RBee Jul 28 '23 at 18:17

1 Answers1

1

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...');
})
QasemBSK
  • 190
  • 8