Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Internet connection on a Cordova App?

I tried some suggestions, such as navigator.onLine, but even in flight mode, my app "thinks" its online.

I found some suggestions with ajax too, but I just want to check if I'm online to open an external web page. If not, I intend to show a message such as "Your device seems to be offline. Check your connection!".

like image 828
Geziel Carvalho Avatar asked Aug 02 '16 12:08

Geziel Carvalho


3 Answers

The best approach is to use cordova network information plugin which does the job for you seamlessly. This plugin provides information about the device's cellular and wifi connection, and whether the device has an internet connection.

You check out the official github page of this plugin for more info on the same. Hope it helps.

like image 126
Gandhi Avatar answered Oct 08 '22 18:10

Gandhi


Download the plugin: https://www.npmjs.com/package/cordova-plugin-network-information

And Try This.

document.addEventListener("deviceready", function(e){
        console.log(navigator.connection.type);
        document.addEventListener("offline", function(e){
                            alert("NO_NETWORK");

        }, false);  
}, false);  

offline

The event fires when an application goes offline, and the device is not connected to the Internet.

document.addEventListener("offline", yourCallbackFunction, false);
like image 36
Tuhin Avatar answered Oct 08 '22 18:10

Tuhin


you can use this plugin

then you can use it everywhere in your App without to import it

if(navigator.connection.type === 'none') {
   alert('there is no internet')
 }

and you can add it into setInterval to check for internet connection every 5 seconds

  setInterval(() => {
        if(navigator.connection.type === 'none') {
            alert('there is no internet')
        } }, 5000);

there are another values for "avigator.connection.type" for example when there is internet then the value of "avigator.connection.type" is the type of connection (wifi, 4g, 3g, ethernet on windows .... )

like image 36
Ali Mohammad Avatar answered Oct 08 '22 19:10

Ali Mohammad