Alert box when no internet connection - Phonegap

Rvervuurt picture Rvervuurt · Apr 4, 2012 · Viewed 33.4k times · Source

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? :)

Answer

edcs picture edcs · Oct 11, 2012

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