JSFiddle - React, Tailwind, and code Playground
Check device connection (Cordova with fallback)
by tonytlwu
HTML
<button id="check">Check connectivity</button>
JavaScript
/* Please add flCheckDeviceIsOnline to the master theme so the function is available for all templates */
function flCheckDeviceIsOnline( yes, no ){
/**
* flCheckDeviceIsOnline( yes, no )
*
* Asynchronously checks if the device is online and runs the relevant callback
*
* @parameter yes Function Function to run if the device is online
* @parameter no Function Function to run if the device is offline (optional)
**/
if ( typeof navigator.connection === 'undefined' ) {
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(e){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(e){
if(no instanceof Function){
no();
}
}
xhr.open("GET","https://studio.fliplet.com/ws/get_available_editions",true);
try {
xhr.send();
} catch (err) {
if(no instanceof Function){
no();
}
}
} else {
var online = navigator.connection.indexOf('Connection.') > -1 && navigator.connection !== 'Connection.NONE';
if ( online ) {
if(yes instanceof Function){
yes();
}
} else {
if(no instanceof Function){
no();
}
}
}
}
document.getElementById('check').addEventListener('click',function(){
flCheckDeviceIsOnline(function(){
alert('Device is online');
},function(){
alert('Device is offline');
});
});