Checking internet connection in PhoneGap app - ios

I am trying to figure out if the device is connected to the internet when the app is started.
As far as I have read, the javascript code should be something like this:
function isOnline() {
var networkState = navigator.network.connection.type;
if (networkState == Connection.NONE) {
return false;
};
return true;
}
I have only tried it on iOS so far.
Unfortunately, navigator.network is undefined.
I know that I have to add the network module in the config.xml file.
According to the PhoneGap page (http://docs.phonegap.com/en/3.0.0/cordova_connection_connection.md.html),
this is the way I did it:
<feature name="NetworkStatus">
<param name="ios-package" value="CDVConnection" />
</feature>
<feature name="NetworkStatus">
<param name="android-package" value="org.apache.cordova.NetworkManager" />
</feature>
Does anybody know what I am missing?

try this one.
install this cordova plugin here.
https://github.com/apache/cordova-plugin-network-information
and add this code into js file
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
isOnline();
}
function isOnline() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
if ((states[networkState]) == states[Connection.NONE]) {
alert('No Internet Connection. Click OK to exit app');
navigator.app.exitApp();
}
}

try this one:
function checkConnection() {
return navigator.connection.type === "none" || navigator.network.connection.type === null ||
navigator.connection.type === "unknown" ? false : true;
}
And remember to check this AFTER device ready event has fired.

Related

Firebase Notifcation [IOS] not working when app is in background

Using:
xcode 10.3
firebase plugin ( https://www.npmjs.com/package/cordova-plugin-fcm )
cordova version 8.1.2
The xcode console shows:
app enters background
Set state background
Disconnected from FCM
What do I have:
Push notification enable on the app(on https://developer.apple.com/)
All the keys/Certificates
I get the token identifier on the iphone, so I suppose it's working but I'm not sure since when you get a notification with the app opened it does show the notification ( Also if someone knows how to fix it, I would appreciate it) but my question is how to stop from disconnecting the FCM plugin when the app goes to background.
Only code I have
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Ligação desconhecida';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'Sem ligação a internet';
if (states[networkState] === states[Connection.NONE]) {
alert("A aplicação necessida de internet para funcionar correctamente");
}
}
FCMPlugin.getToken(function (token) {
myToken = token;
alert(token);
}, function (error) {
console.error(error);
});
}

Offline and online events not getting Called in cordova 3.5.0

I am using cordova 3.5.0 to develop my phonegap application . In that i want to check internet connectivity before web service calls . So i added network status plugin by using the command cordova plugin add org.apache.cordova.network-information . Plugin installed successfully in my application .
After Adding the plugins i added 2 EventListener's one for online and another for offline.
var app = {
// Application Constructor
initialize: function() {
console.log('App initializing...');
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
//This is to allow testing in desktop browser where there is no device ready event
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
} else {
this.onDeviceReady();
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
require(['router'], function(Router){
Router.getInstance();
console.log('Backbone callback...');
});
}
};
So i used another method to check online status as mentioned in Phonegap documentation
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
which is always returning the mode am connected to internet for e.g "WiFi connection" . Though i changed my disconnected my internet connection .
Help me resolving this issue .
I had the same problem: the online/offline event was not firing, and sometimes when it went offline, the app crashed...
THE SOLUTION:
- The appropriate permission tag must bem IMMEDIATELY after the tag , in the AndroidManifest.xml file... it may appear ridiculous, but otherwise the event was not firing.
In the end, your file will look like:
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" android:windowSoftInputMode="adjustPan" package="br.com.burkard.app" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
Scope.
document.addEventListener("offline", this.onOffline, false);
document.addEventListener("online", this.onOnline, false);
I avoid using the network types, as I found they do not work consistently on all platforms.
Instead I use:
isOnline = function() {
try {
if (!navigator.onLine){
return false;
} else {
return true;
}
}
catch(e) {
alert('An error has occurred: '+e.message);
}
};
I would do to things.
First add the online and offline eventlisteners only in the onDeviceReady function,
Second, add scope to the onOffline and onOnline method calls in the event listeners.
Something like this:
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
document.addEventListener("offline", app.onOffline, false);
document.addEventListener("online", app.onOnline, false);
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},

check internet connection with phonegap

I am seeing a few different options to check internet connection with phonegap. There is document.addEventListener("online", onOnline, false); and there is also navigator.network.connection.type... but I am not sure which one is best practice. I would also like to be able to prevent the bad case where the phone is connected to a wifi network but has no internet connection.
$(document).on('pagecreate','#explanation-short', function(){
if ( isPhoneGap() ) {
if (checkConnection() == "none" ) {
connectionStatus = 'offline';
} else {
connectionStatus = 'online';
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
//console.log('Connection : ' + Connection);
//console.log('Connection type: ' + states[networkState]);
return networkState;
}
} else {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}
console.log("connectionStatus : "+connectionStatus);
});
For example, this code works if the phone is connected to the wifi, but we are not sure the internet is actually available.
What are the best practices with phonegap 3.3+ and Jquery mobile 1.4 ?
The event,
document.addEventListener("online", onOnline, false);
is only fired when your app is already is loaded and regains a connection. This is not fired on start of the application.
Therefore, you have to use the checkConnection() method on start of your application and then if you need to check later while the app is running, you use the event listener.
Inside device ready function , I use the following lines to check for internet connection
if(navigator.connection.type==0)
{
alert('This application requires internet. Please connect to the internet.');
}
else if(navigator.connection.type=='none')
{
alert('This application requires internet. Please connect to the internet.');
}
else
{
//Hurray I'm online
}
Currently this is serving me quite well. But I still don't have that way to detect connected wifi,but no internet.I would also like to know how to detect that.
In Phonegap there are two event listeners 'online' & 'offline'. use them for fast response.Please check Example :
var internet;
document.addEventListener('online',online,false);
document.addEventListener('offline',offline,false);
function online(){
internet=true;
}
function offline(){
internet=false;
}
if(internet){
// internet is connected
}else{
// internet is not connected
}
for more details please visit http://docs.phonegap.com/en/3.0.0/cordova_events_events.md.html

Display custom message if url fails to load in phonegap inappbrowser

I have created an android app that basically loads the responsive website via phonegap inappbrowser.
Now i want to fancy it up and make it more like an app. So my main problems are
When i try to load the app and somehow internet goes off, it displays the url of the website and says website not available. So i want to remove that and display my own custom message. Is that possible? What do i need to do for that?
Whenever user clicks on any menu item of the website from the app it gives a blank screen during the page transition/load. Now is there anyway i can show a loading sign every time they click on a menu item?
This is what i am using
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var ref = window.open('http://www.google.com', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: Please Check your Internet Connection. '); });
ref.addEventListener('exit', function() { alert(event.type); });
}
</script>
I am using dreamweaver to deal with the html section and phonegap build to compile my app.
I am fairly new at this so please elaborate.
function onDeviceReady()
{
checkConnection();
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
if(states[networkState]==states[Connection.NONE])
{alert('No Internet Connection! Please Turn on Wifi or Mobile Data to use this application');}
else
{
var ref = window.open('http://www.google.com', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: Please Check your Internet Connection. '); });
ref.addEventListener('exit', function() { alert(event.type); });
}
}
So what if the internet gets turned off in the middle of using the app? Would it work then too? If not then is there any way to get that done too?
Also can you please tell me where to apply the following codes that you had put on your response
navigator.notification.activityStart("Please Wait", "Its loading your homepage.....");
Below code will stop the loading popup :
navigator.notification.activityStop();
Thank you very much. I really am in need for these 2 solutions :(
Hi Finally for me works
onerror function is called when the browser hasn't internet.
onload function is called when exist a internet connection.
<body>
<script>document.write('<img src="http://static.forosdelweb.com/fdwtheme/logo-navidad.png?'+Math.random()+'" style="display:none" onload="alert("hay internet")" onerror="alert("no hay internet")" />');</script>
</body>
You can Check internet connection onDeviceReady function with following code.
function onDeviceReady()
{
checkConnection();
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
if(states[networkState]==states[Connection.NONE])
{alert('No Internet Connection! Please Turn on Wifi or Mobile Data to use this application');}
else
{
//load your pages
}
}
Now if you are loading responsive site then you need to specify loader in that responsive website. But in cordova you can use following code for loader
navigator.notification.activityStart("Please Wait", "Its loading your homepage.....");
Below code will stop the loading popup :
navigator.notification.activityStop();

Phonegap show html if not connected

Here is my code at the minute:
Using phonegap 2.9
<head>
</head>
<body>
<script charset="utf-8" src="js/cordova.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
}
// Handle the online event
//
function onOnline() {
document.location = 'http://app.dadad.com';
}
function onOffline() {
console.log("Offline");
}
</script>
</body>
However right now I just get a white screen whether i'm connected or not. Eventually what I would like is to display some html when the user is not connected.
So in conclusion:
Would like to fix the function as it is not working
Would like to show html when not connected.
The Online/Offline events do not fire onload. They are there for when you are in app (complete load) and then lose or gain connection. I have gotten around this by doing an initial connection check on load, like this:
function checkConnetcion() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = false;
states[Connection.ETHERNET] = true;
states[Connection.WIFI] = true;
states[Connection.CELL_2G] = true;
states[Connection.CELL_3G] = true;
states[Connection.CELL_4G] = true;
states[Connection.CELL] = true;
states[Connection.NONE] = false;
var connectionStatus = states[networkState];
if(connectionStatus) {
//Do something if connected
}
else{
//Do something if not connected
}
}
Then add this your onready function:
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
checkConnetcion();
}
You can make use of Jquery ajax and send a dummy request before sending actual request. If you get and Error Code as '0' it means there is no internet connectivity.
$.ajax({
url: 'TestUrl',
type: 'GET',
success: function (data) {
// Go ahead with you request
},
error: function (x, y, z) {
if (x.status == 0) {
alert("Please connect to the internet");
}
else{
alert("Other Error Occured")
}
}
});
Secondly you can also make you of HTML 5 navigator
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
But it will show ONLINE when WIFI doesn't provide Internet connection.
Cordova connection object will also show WIFI if there is no internet connection

Resources