手机网络检测与监听网络连接和断开事件

手机网络会经常随着环境和用户的设置发生改变,如果要为用户提供更友好的操作和体验,则在有些情况下需要进行网络检测,即时处理网络断开的情况

网络检测插件提供了检测当前网络和监听网络变化的js接口

网络检测功能介绍说明

监听联网时变化

document.addEventListener("online", function(){alert('connect');}, false);

监听断网时变化

document.addEventListener("offline", function(){alert('disconnect');}, false);

检查当前网络连接情况,查看网络连接类型

var networkState = navigator.connection.type;

网络连接的类型定义有

Connection.UNKNOWN
Connection.ETHERNET
Connection.WIFI 
Connection.CELL_2G
Connection.CELL_3G
Connection.CELL_4G
Connection.CELL 
Connection.NONE

显示当前的网络类型的简单例子

alert(navigator.connection.type);

网络检测功能完整例子代码

<!DOCTYPE>
<html>
	<head>
		<title>lbuilder demo</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
		<meta http-equiv="Cache-Control" content="no-siteapp"/>
		<script type="text/javascript">
		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.CELL]     = 'Cell generic connection';
		    states[Connection.NONE]     = 'No network connection';
		    alert('Connection type: ' + states[networkState]);
		}
		document.addEventListener("offline", function(){alert('disconnect');}, false);
		document.addEventListener("online", function(){alert('connect');}, false);
		</script>
	</head>
<body>
	<h3>Lbuilder demo</h3>
	<a href="javascript:checkConnection();" >check network</a><br/><br/>
</body>
</html>