How to determine whether the device is connected to internet in Ionic 3?

I am developing Ionic 3 application for both Android and iOS. I am using ionic-native/network plugin. This plugin only provides the onDisconnect() and onConnect() hook. So, using this plugin i won’t know that the device has internet connection while opening the application for the first time.

Then, i tried to implement cordova-plugin-network-information like below:

export class MyApp {
 navigator: any;
 Connection: any;
 constructor(private platform: Platform, private statusBar: StatusBar, private helperProvider: HelperProvider) {
   this.platform.ready().then(() => {
      this.statusBar.hide();
      let networkState = this.navigator.connection.type;
      if (this.Connection.NONE == networkState) {
        this.helperProvider.createToast('No internet connection.', 'bottom', 5000, 'toast-error', true, 'Ok');
      }
    });
  }
}

But, i am getting below error:

Runtime Error:
Uncaught (in promise): TypeError: Cannot read property ‘connection’ of undefined TypeError.

Can anyone help me on this?

1 Like

I mean, your error message tells you exactly what the error is, I’m not sure what you’re looking for.

navigator is undefined because you never assigned anything to it, so you can’t access navigator.connection.

1 Like

I’m interested in this topic too.

1 Like

I know navigator is undefined. But why? I am calling the navigator when the platform is ready.

this.navigator is undefined because you never assign anything to it, like I said in my original comment.

You wrote this line of code right?

navigator: any

So you show me where you assign a value to that.

The ionic native plugin that you say “only provides onDisconnect() and onConnect()” also very clearly has a connection type variable that you can use to determine the connection type, it will be one of unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none. That’s written right in the docs. https://ionicframework.com/docs/native/network/#advanced

So…why not just use that?

1 Like

if(this.network.type === ‘none’){
this.router.navigate([‘/networkcheck’]); //write ur code here

  }

if(this.network.type === ‘none’){
this.router.navigate([’/networkcheck’]);
}

1 Like