Check Internet Connection in Ionic

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

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.

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});

And of course you can do the same with online listener to check when internet connection returns

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

Senior Software Engineer at 99x | Freelance developer | Interested in History and Philosophy