Check Internet Connection in Ionic

Athif Shaffy
Nov 3, 2018 · 1 min read

If you google “checking internet connection in Ionic” you might probably be asked to use the Ionic Network module.

Instead of using any modules/libraries, it is possible to check the internet connection with JavaScript and Angular itself. I will show you how in this post.

Check for Internet Connection on App launch

In the app.component.ts file if you add the following code to the constructor.

public onlineOffline: boolean = navigator.onLine;

This makes use of the Angular’s navigator global object to check for internet connectivity. The navigator.onLine returns a Boolean, true if there is internet connection and false when there is no connection. An example of this being used is shown below.

if (!navigator.onLine) {//Do task when no internet connection}

Check for internet connection when app is being used.

When the app is running and being used, if there is no internet connection, we could use the JavaScript’s own Window object.

Adding the following code in the app.component.ts’s constructor. will check if the application went offline when application is being used.

window.addEventListener('offline', () => {//Do task when no internet connection});

Athif Shaffy

Written by

Curious Software Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade