I am trying to write a component that will detect whether the app is online or offline so it can trigger another event. Is there a built-in function that can be leveraged?
Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.
Ping is a network administration utility or tool used to test connectivity on an Internet Protocol (IP) network.
JavaScript has a function called navigator. This browser property can be used to determine if you are connected to the internet. It returns true or false depending on the status of the client's network and says whether the browser is online or offline easily.
To be notified of the app coming online or going offline, rely on the online/offline events
online$ = fromEvent(window, 'online');
offline$ = fromEvent(window, 'offline');
Chain your other events to these:
online$.subscribe(e => this.syncWithServer());
Also see this article about navigator.onLine
. Note that browsers don't implement this event uniformly. In some cases, "online" just means that the browser is connected to a local network, not the internet. To get more reliable information, you may need to test by trying to ping a remote server when the event fires.
online$ = fromEvent(window, 'online').pipe(
switchMap(e => this.pingServer()),
filter(e => e)
);
offline$ = fromEvent(window, 'offline').pipe(
switchMap(e => this.pingServer()),
filter(e => !e)
);
Where pingServer
will make a remote request and return an observable that emits true
when the request is successful, or false
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With