Check Internet Connection in Ionic

Athif Shaffy
2 min readNov 3, 2018

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

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

--

--

Athif Shaffy

Senior Software Engineer | Freelance developer | Interested in History and Philosophy