How to Do Internet Checking in browser and Also in Cordova App in Ionic 6?

In this blog, we will discuss how to check the network in the browser. We will also show how to check the network in the Cordova app in Ionic 6 as well. Please check the following steps to find out the solutions.

Step 1:

Please add the following code to your service class.

async getnetworkStatus(){
return new Promise((resolve,reject)=>{
if(!navigator.onLine){
this.noNetwork = true;
}else{
this.noNetwork = false;
}
window.addEventListener('offline', () => {
this.noNetwork = true;
});
window.addEventListener('online', () => {
this.noNetwork = false;
});
console.log(this.noNetwork);
resolve(this.noNetwork);
})
}

This code returns the true or false as network checking. If it is false then it says you have a proper internet connection. If it is true then you understand that you do not have an internet connection. Therefore, this coder runs into the browser fluently.

But in your app, it not works. But I am giving a solution to how we use this code in your android build.

Step 2:

Just need to add the following code to go to another step.

ionic Cordova plugin add Cordova-plugin-network-information

npm install @ionic-native/network
 

Just need to install Cordova plug-ins.

Step3:

Please add the following code.

import { Network } from '@ionic-native/network/ngx';

Just import this line add it to your app.module.ts. Therefore, add network as provider section.

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
AppRoutingModule,
HttpClientModule],
providers: [Geolocation,Camera,SplashScreen,StatusBar,Network,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent],
})
export class AppModule {}

Now, call this following function in your page.ts file. Where do you think it requires?

await this.dataServ.getnetworkStatus()

Conclusion:

Only Using installation file and import into the app module file and it works in the Android app. In this code, you do not need to write any Cordova-related code for Internet checking. So, this is all from my end. Please read the blog and share your feedback in the comment section.

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.