使用JS在客戶端判斷當前網絡狀態

1. navigator.onLine

經過navigator.onLine判斷當前網絡狀態:javascript

1
2
3
4
5
if(navigator.onLine){
...
}else{
...
}

 

很是簡單,可是並不許確-根據MDN的描述:
navigator.onLine只會在機器未鏈接到局域網或路由器時返回false,其餘狀況下均返回true
也就是說,機器鏈接上路由器後,即便這個路由器沒聯通網絡,navigator.onLine仍然返回true。html

2. ajax請求

採用get請求的方式,根據返回值判斷是否可以成功get到數據,從而肯定當前的網絡狀態:java

1
2
3
4
5
6
7
8
9
$.ajax({
url: 'x.html',
success: function(result){
...
},
error: function(result){
...
}
});

 

3. 獲取網絡資源

原理同2,在頁面放一張隱藏圖片,設置其onerror函數(獲取圖片資源失敗時會調用該函數):jquery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script src="./jquery-3.1.1.min.js"></script>
<script>
function getImgError(){
alert("Network disconnect!");
}
$().ready(function(){
$("#btn-test").click(function(){
var imgPath = "https://www.baidu.com/img/bd_logo1.png";
var timeStamp = Date.parse(new Date());
$("#img-test").attr("src", imgPath + "?timestamp=" + timeStamp);
});
});
</script>
<body>
<img id="img-test" style="display:none;" onerror="getImgError()"/>
<button id="btn-test">check status</button>
</body>

 

每次點擊button時,更新該圖片的src。若獲取圖片失敗,則認爲網絡鏈接失敗。ajax

PS: 三種方法都不是很理想,但暫時還沒有找到更好的解決方案。網絡

相關文章
相關標籤/搜索