1

I want to test if the user has an active internet connection.

I know we can do it with navigator.Online, but I don't think it works when the user has a limited WiFi network.

I need to show a popup if the user has been disconnected/has a limited WiFi network

Melchia
  • 22,578
  • 22
  • 103
  • 117
Bilal Shah
  • 79
  • 4
  • 1
    Does this answer your question? [Detect the Internet connection is offline?](https://stackoverflow.com/questions/189430/detect-the-internet-connection-is-offline) – Alwaysblue Nov 01 '19 at 13:55

4 Answers4

0

XHR Requests

Try making an XHR request to the same website itself (or maybe even a couple of XHR requests), and check if it fails, and if it does, you can safely conclude that the user does not have an active internet connection.

Community
  • 1
  • 1
Vishnu S.
  • 141
  • 1
  • 2
  • 8
0

You can use this one npm package ng-connection-service

after that you can easily use next code into your root app component:

constructor (private connectionService: ConnectionService) {
        this.connectionService.monitor().subscribe((isConnected: boolean) => {
            if (!isConnected) {
                alert('oops you have no Internet connection');
            }
        });
}
Taras Kovalenko
  • 2,323
  • 3
  • 24
  • 49
0

you can create a function like this :

const checkConnection = () => fetch('https://google.com')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP status ' + response.status);
            }
            return response;
        })
        .then(response => 'online')
        .catch(error => 'offline');

And use it like this:

const isOnline = await checkConnection() === 'online';
Melchia
  • 22,578
  • 22
  • 103
  • 117
0

There's a native way that's supported almost everywhere:

const isOnline = ('onLine' in navigator) ? navigator.onLine : true

And a pair of event listeners:

window.addEventListener('online', () => {
    isOnline = true
})

window.addEventListener('offline', () => {
    isOnline = false
})
Egor Litvinchuk
  • 1,800
  • 2
  • 14
  • 15