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
Related
i am need one help. i make a broker with node red and i am using mqtt ws. I tested in Hivemq website and all works good, but in my website i do publish only, and nothing received. i am using mqttws31.js. in my javascript console show conected, and i can publish but never read. Somebody help me? bellow my code. sorry for my english.\
var mqtt;
var reconnectTimeout = 2000;
var host="my_broker"; //change this
var port=9001;
function onFailure(msg) {
alert(msg);
console.log("Connection Attempt to Host "+host+"Failed");
setTimeout(MQTTconnect, reconnectTimeout);
}
function onMessageArrived(msg){
out_msg="Message received "+ msg.payloadString+"<br>";
out_msg=out_msg+"Message received Topic "+msg.destinationName;
console.log(out_msg);
document.write(msg.payloadString);
// funcoes executar
if (msg.destinationName == "voltas") {
// Temperatura
alert(msg.payloadString);
}
}
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected ");
}
function MQTTconnect() {
//console.log("connecting to "+ host +" "+ port);
var x=Math.floor(Math.random() * 10000);
var cname="orderform-"+x;
mqtt = new Paho.MQTT.Client(host,port,cname);
//document.write("connecting to "+ host);
var options = {
timeout: 3,
onSuccess: onConnect,
onFailure: onFailure,
};
mqtt.onMessageArrived = onMessageArrived
mqtt.connect(options); //connect
}
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);
});
}
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");
},
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();
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.