Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple example showing how to use network API
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" id="viewport" content="width=device-width,height=device-height,initial-scale=1.0,user-scalable=no">
<script src="json2.js" type="text/javascript"></script>
<script src="phonegap.js" type="text/javascript"></script>
<script type="text/javascript">
// invoked when device is ready
function deviceInfo() {
document.getElementById('window.device.phonegap').innerHTML = 'window.device.phonegap = ' + window.device.phonegap;
document.addEventListener("online", doOnline, false);
document.addEventListener("offline", doOffline, false);
checkNetworkType();
}
// invoked when application is online
function doOnline() {
console.log('Event: online\n' + 'Network Type: ' + navigator.network.connection.type + '\n');
checkNetworkType();
}
// invoked when application is offline
function doOffline() {
console.log('Event: offline\n' + 'Network Type: ' + navigator.network.connection.type + '\n');
checkNetworkType();
}
// register PhoneGap event listeners when DOM content loaded
function init() {
console.log('init()');
document.addEventListener("deviceready", deviceInfo, true);
}
function checkNetworkType() {
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 (navigator.network.connection.type === Connection.UNKNOWN ||
navigator.network.connection.type === Connection.NONE) {
alert("No connection available");
} else {
alert("Connection Type: " + states[navigator.network.connection.type]);
}
}
</script>
<title>Insert title here</title>
</head>
<body onload="init()">
<h3>window.device</h3>
<p id="window.device.phonegap">[window.device.phonegap]</p>
<input type="button" value="Check Network" onclick="checkNetworkType();return false;" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment