浏览器检测,移动网络的在线离线及网络状态
2012-07-17 17:41 vanillalyx 阅读(1170) 评论(1) 编辑 收藏 举报使用JS变量 navigator.onLine 是true还是false,可以判断在线还是离线。
不知道是不是html5的功能,在IE7,FF,Chrome下都是ok的。
如果你还想知道网络状况是wifi,还是2G,3G什么的,有少数部分浏览器支持network information api
network information api 链接 http://www.w3.org/TR/netinfo-api/
浏览器支持情况 链接 http://mobilehtml5.org/ (这个内容很给力,html5的功能支持情况概览)
不过api文档说的接口属性好像不是那么回事。
我在android 2.3.6内置浏览器测试得出以下结论:
navigator.connection的属性有下面这几个
type 这个就表示当前网络状态了,值是下面几个常量中的一个。
UNKNOWN = 0
ETHERNET = 1
WIFI = 2
CELL_2G = 3
CELL_3G = 4
UC浏览器无此变量。
QQ浏览器有此变量,不过检测出来的type是0
至于online offline事件检测,可以通过监控下面的事件进行检测:
在android2.3.6内置浏览器测试通过,QQ浏览器测试不通过。
window.addEventListener('online' , function(){alert('online');},false);
window.addEventListener('offline' , function(){alert('offline');},false);
online,offline事件官方说明:
http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html
Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.
The events online
and offline
are fired when the value of this attribute changes.
The navigator.onLine
attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.
When the value that would be returned by the navigator.onLine
attribute of a Window
or WorkerGlobalScope
changes from true to false, the user agent must queue a task to fire a simple eventnamed offline
at the Window
or WorkerGlobalScope
object.