Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert box when no internet connection - Phonegap

I'm trying to get a pop-up to, well, pop up when there is no internet connection on the device.

I got the following example working, but now I want the alert only to show when the result is "No network connection".

I tried this:

if (states[Connection.NONE]){
       alert('Geen internet :(');
       };

But that just makes the alert-box pop up, no matter if there is a connection or not. Who can help me? :)

like image 426
Rvervuurt Avatar asked Apr 04 '12 10:04

Rvervuurt


2 Answers

Old-ish question, but here's how I'd do it - You can use events to detect if the device is online or offline. This is ideal for this situation as the pop-up will appear as soon as the device goes offline:

document.addEventListener("offline", function(){ alert("You're offline") }, false);

And to do the same, but when the device regains an internet connection?:

document.addEventListener("online", function(){ alert("You're online") }, false);

Check out the events docs here: http://docs.phonegap.com/en/1.8.1/cordova_events_events.md.html#offline

UPDATE :

as of cordova 5 these events have been moved to cordova-plugin-network-information

like image 174
edcs Avatar answered Nov 18 '22 18:11

edcs


if you do

if (states[Connection.NONE]){
   alert('Geen internet :(');
   };

this would happen.
do this.

networkState = navigator.network.connection.type
alert(states[networkState]);

see if this works for u or not.

EDIT: just compare:

if (networkState == Connection.NONE){
  alert('no internet ');
};
like image 24
ghostCoder Avatar answered Nov 18 '22 20:11

ghostCoder