How to alert the user when there's no internet connection - extjs

I need to alert the user with the following conditions;
Request timed out
No internet connection
Unable to reach the server
Here's the code; How to capture the following conditions when occurred and alert the user ?
failure: function (response) {
var text = response.responseText;
console.log("FAILED");
},success: function (response) {
var text = response.responseText;
console.log("SUCCESS");
}
I tried the following code to check if the internet is reachable, but it didn't work
var networkState = navigator.network.connection.type
alert(states[networkState]);
if (networkState == Connection.NONE){
alert('No internet ');
};
UPDATE **
I added the following in my index.html, but, when i disable WIFI, i don't see the alert popping.
<script>
function onDeviceReady() {
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
}
</script>

The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.
For instance, your "deviceready" callback:
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.

Exactly as Simon said, you can use
document.addEventListener("offline", youCallbackFn, false);
or you can interrogate the boolean property
navigator.onLine
(Should return true or false)
However, this technique will tell you whether device is connected. The caveat is such that device can be connected to WiFi, but the router might be offline. In that case, use a polling mechanism, like timely Ext.Ajax.request with lower timeouts. Timeout expired = offline.

You can use PhoneGap's NETWORK API
The network object gives access to the device's cellular and wifi connection information.
You can test it in the following way,
function onDeviceReady() {
navigator.network.isReachable("phonegap.com", reachableCallback, {});
}
// Check network status
//
function reachableCallback(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
alert('Connection type: ' + states[networkState]);
}

You can add 'Ext.device.Connection' in app.js of your application. And check your device is online or offline using code:
if (Ext.device.Connection.isOnline()) {
alert('Connected to internet');
}
else{
alert('You are not connected to internet');
}

Just Embed this in your tag
<body onoffline="alert('PLEASE CHECK YOUR INTERNET SETTING');">

Related

RTCPeerConnection and createDataChannel not working for Edge

I have been working on an application where when a person logs into an account, the IP address of the device is stored in the backend and local storage. Then when a person logs into the same account from another browser or so, it will show a popup with the last login IP address. It seems to work on chrome and Mozilla but not working in edge browser. It always returns null because it's not entering the code after pc.createDataChannel.
The code snippet is as below.
const getIpAddress = state => {
window.RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;
let ip = false;
if (window.RTCPeerConnection) {
ip = [];
var pc = new RTCPeerConnection({ iceServers: [] }), noop = function
() {
};
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function (event) {
if (event && event.candidate && event.candidate.candidate) {
var s = event.candidate.candidate.split('\n');
ip.push(s[0].split(' ')[4]);
localStorage.setItem('ipV4Address', ip[0]);
}
};
}
return state;
};
I also tried using adapter js but not sure how to exactly use it.
WebRTC Peer-to-peer connections not yet supported fully on Edge v18 browser yet. You can check your browser compatible at Can I use RTCPeerConnection ?
It seems that there is no way to actually get the private ip in edge browser, so had to use a third party api to get public ip and use that.

CouchDB sync error net::ERR_CONNECTION_RESET

I am trying to sync a local PouchDB instance with a remote CouchDB instance on Google App Engine.
I have successfully logged in to the remote instance, but I am getting the following error when I try to sync:
replication paused (e.g. user went offline)
pouchdb-6.3.4.min.js:9 GET https://<ipaddress>:6984/pouchnotes/ net::ERR_CONNECTION_RESET
Sync function
PouchNotesObj.prototype.syncnoteset = function (start, end) {
var start = new Date().getTime();
document.getElementById("syncbutton").innerHTML = "Syncing...";
var i,
that = this,
options = {
doc_ids:['1450853987668']
};
if(start){ options.startkey = start; }
if(end){ options.endkey = end; }
PouchDB.sync(this.dbname, this.remote, { retry: true })
.on('change', function (info) {
console.log('change');
document.getElementById("syncbutton").innerHTML = "Sync Notes";
}).on('paused', function () {
console.log('replication paused (e.g. user went offline)');
document.getElementById("syncbutton").innerHTML = "Sync Notes";
}).on('active', function () {
console.log('replicate resumed (e.g. user went back online)');
document.getElementById("syncbutton").innerHTML = "Sync Notes";
}).on('denied', function (info) {
console.log('a document failed to replicate, e.g. due to permissions');
document.getElementById("syncbutton").innerHTML = "Sync Notes";
}).on('complete', function (info) {
console.log("Sync Complete");
document.getElementById("syncbutton").innerHTML = "Sync Notes";
that.viewnoteset();
that.formobject.reset();
that.show(that.formobject.dataset.show);
that.hide(that.formobject.dataset.hide);
var end = new Date().getTime();
console.log("Time Taken - " + (end - start) + " ms");
}).on('error', function (error) {
console.log("Sync Error:" + JSON.stringify(error));
alert("Sync Error:" + error);
that.showerror(error);
});
}
Edited to add: do I need to set this up?
It turned out that I had not configured the firewall correctly.
For anyone else who stumbles across this issue: you only need SSH tunnelling to access Fauxton on localhost. You don't need it to access the API.
If you want to access the API via https, the port is 6984 (not 5984), and for a non-Google App Engine server, you need something like Nginx set up to provide a SSL certificate. On Google App Engine, SSL certificates are provided.
But you still need to configure CouchDB to enable SSL.
Thanks to the guys at the CouchDB user mailing list for their input.

SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd. index.html

I am using Visual studio 2015 and ionic and i have been able to build for windows phone 8.1. I created a login page that is to query a php on a different server but i get a problem like this SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
index.html
error. My code trying to make a request is
var login = function(name, pw) {
return $q(function(resolve, reject) {
$http.post('http://192.167.180.1//logn/sear.php',{ 'pin': pw }).then(
function(result) {
// No result here..
var re=result.data.split(",");
console.log(re[3]);
if ((re[0] == 0 )) {
// Make a request and receive your auth token from your server
storeUserCredentials(re[2]);
useCredentials(re[1]+" "+re[3]+" "+re[4]);
console.log(LOCAL_TOKEN_KEY);
resolve('Login success.');
} else if(result.data == 1) {
reject('Login Failed.');
}
}, function(err) {
// $scope.response = err.records;
console.log("error");
});
});
};
When you are facing this error while building a Win 8 Phone App, you might want to add private network capability to app manifest.
Credits for the guy who helped me out: https://sonyarouje.com/tag/network-error/
- there you'll find step-by-step instruction how to do it.
There is also another answer how to do it on SO:
WinJS.xhr: Network Error 0x2efd, Could not complete the operation due to error 00002efd

My firebase connection test fires connected and disconnected

I am using the firebase connection connection test detection script to show a modal if the user has disconnected but for some reason when the app loads it fires both cases and it shows the disconnected modal even though it has connection. What am I doing wrong.
var firebaseRef = new Firebase(FIREBAE_URL);
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
if (connectedSnap.val() === true) {
console.log("connected");
} else {
console.log("not connected");
setTimeout(function(){
$ionicPopup.show({
title: 'Network is either down or poor wifi',
template: 'Either pay for some wifi or go to a cafe',
buttons: [{
text: '<b>ok</b>',
type: 'button-positive'
}]
});
}, 8000)
}
});
When you first create a Firebase client, it starts building a connection to the server. This can take some time. Until the connection is fully established, the client is not connected. To it fires false value in .info/connected.
Showing a modal dialog whenever the user loses their connection is probably a bad user experience. Network connections on mobile devices drop surprisingly regularly and Firebase shields the user from brief interruptions effortlessly. Showing a modal dialog is like screaming "YOU'RE OFFLINE, WE'RE ALL DOOMED, YOU HAVE NO INTERNET" in their face. Hardly a pleasant experience.
A more typical usage of .info/connected is to show a less obtrusive indicator, such as a little status icon. Alternatively you can show a modal if the user has been offline for a certain period.
I don't have enough reputation to reply to your comment asking how to avoid the first false event, and I'm not sure if you still want an answer to this, but something simple like this should do the trick:
var wasPreviouslyConnected = false;
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
if (connectedSnap.val() === true) {
wasPreviouslyConnected = true;
console.log("connected");
}
else if (wasPreviouslyConnected) {
console.log("disconnected")
}
else {
console.log("initial false connected snapshot while data is still loading");
}
});

Connection state with doowb/angular-pusher

I am trying to build an Angular project with Pusher using the angular-pusher wrapper. It's working well but I need to detect when the user loses internet briefly so that they can retrieve missed changes to data from my server.
It looks like the way to handle this is to reload the data on Pusher.connection.state('connected'...) but this does not seem to work with angular-pusher - I am receiving "Pusher.connection" is undefined.
Here is my code:
angular.module('respondersapp', ['doowb.angular-pusher']).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('Foooooooo')
.setOptions({});
}
]);
var ResponderController = function($scope, $http, Pusher) {
$scope.responders = [];
Pusher.subscribe('responders', 'status', function (item) {
// an item was updated. find it in our list and update it.
var found = false;
for (var i = 0; i < $scope.responders.length; i++) {
if ($scope.responders[i].id === item.id) {
found = true;
$scope.responders[i] = item;
break;
}
}
if (!found) {
$scope.responders.push(item);
}
});
Pusher.subscribe('responders', 'unavail', function(item) {
$scope.responders.splice($scope.responders.indexOf(item), 1);
});
var retrieveResponders = function () {
// get a list of responders from the api located at '/api/responders'
console.log('getting responders');
$http.get('/app/dashboard/avail-responders')
.success(function (responders) {
$scope.responders = responders;
});
};
$scope.updateItem = function (item) {
console.log('updating item');
$http.post('/api/responders', item);
};
// load the responders
retrieveResponders();
};
Under this setup how would I go about monitoring connection state? I'm basically trying to replicate the Firebase "catch up" functionality for spotty connections, Firebase was not working overall for me, too confusing trying to manage multiple data sets (not looking to replace back-end at all).
Thanks!
It looks like the Pusher dependency only exposes subscribe and unsubscribe. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L86
However, if you access the PusherService you get access to the Pusher instance (the one provided by the Pusher JS library) using PusherService.then. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L91
I'm not sure why the PusherService provides a level of abstraction and why it doesn't just return the pusher instance. It's probably so that it can add some of the Angular specific functionality ($rootScope.$broadcast and $rootScope.$digest).
Maybe you can set the PusherService as a dependency and access the pusher instance using the following?
PusherService.then(function (pusher) {
var state = pusher.connection.state;
});
To clarify #leggetters answer, you might do something like:
app.controller("MyController", function(PusherService) {
PusherService.then(function(pusher) {
pusher.connection.bind("state_change", function(states) {
console.log("Pusher's state changed from %o to %o", states.previous, states.current);
});
});
});
Also note that pusher-js (which angular-pusher uses) has activityTimeout and pongTimeout configuration to tweak the connection state detection.
From my limited experiments, connection states can't be relied on. With the default values, you can go offline for many seconds and then back online without them being any the wiser.
Even if you lower the configuration values, someone could probably drop offline for just a millisecond and miss a message if they're unlucky.

Resources