Created
January 11, 2012 15:16
-
-
Save purdrew/1595136 to your computer and use it in GitHub Desktop.
Simple example showing how to use network API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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