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

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is React 16 all about?

A beginner’s guide to testing React components using Jest and GitHub Actions

npm weekly #222: Announcing lots of launches!

How to add google map API to your website & Fix google map API Errors

How to add google map API to your website & Fix google map API Errors

MySQL handlersockets and ES2016 async/await.

The middleware, Express.js

npm weekly #196: Join us at FinJS in London, Laurie leads a new webinar next Tuesday, plus tips on…

Top 8 React Native Components Libraries To Help You Accelerate The Software Development Process

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Athif Shaffy

Athif Shaffy

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

More from Medium

Ditching my Array Methods Cheat Sheet

How do JavaScript arrow functions work and when should you use them?

Insertion Sort and Bubble Sort

Javascript: How Web Browser Works?