亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網(wǎng)為廣大站長提供免費收錄網(wǎng)站服務(wù),提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.430618.com 】, 免友鏈快審服務(wù)(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

前言

檢查用戶是否在線已逐漸成為應(yīng)用的基礎(chǔ)功能,因為大多數(shù)網(wǎng)站的用戶界面都在不斷地與網(wǎng)絡(luò)服務(wù)器通信以進(jìn)行數(shù)據(jù)傳輸,如果用戶網(wǎng)絡(luò)斷開,那么應(yīng)用程序的功能就會受到影響。

因此,本文將看到一些檢測用戶何時離線以及用戶何時重新在線以在網(wǎng)站上顯示一些消息來通知用戶的方法。

1.瀏覽器對象模型

在瀏覽器對象模型中有 JAVAScript 對象,這些對象在與瀏覽器交互方面很有用,例如 Window 對象、Navigator 對象、Screen 對象、Document 對象等。本文將使用兩個對象,即:Window對象、Navigator對象來判斷用戶是否斷網(wǎng)。

Navigator.onLine 屬性

Navigator 對象用于與瀏覽器進(jìn)行交互, 可以使用 JavaScript 中的 Navigator 對象獲取有關(guān)瀏覽器的所有信息。Navigator 對象的 onLine 屬性可用于檢查瀏覽器是否連接到互聯(lián)網(wǎng)。

if (navigator.onLine) {
  console.log('在線');
} else {
  console.log('離線');
}

 

該屬性的瀏覽器支持情況如下:

 

看起來形式一片大好,整體支持率達(dá)到了98.79%,即基本所有的瀏覽器都已經(jīng)支持了該屬性,包括IE9!

Window對象的Connection事件

Javascript為Window對象提供了兩個連接事件,分別是:

  • offline:當(dāng)瀏覽器斷網(wǎng)并且 Navigator.onLine 屬性的值變?yōu)?false 時會觸發(fā)
  • online:當(dāng)瀏覽器連接網(wǎng)絡(luò)并且 Navigator.onLine 屬性的值變?yōu)閠rue時觸發(fā)
// 離線事件(方式1)
window.addEventListener('offline', (event) => {
    console.log("The.NETwork connection has been lost.");
});
// 離線事件(方式2)
window.onoffline = (event) => {
  console.log("The network connection has been lost.");
};

除了這兩個事件之外,還將使用 Window 對象的load事件,該事件在瀏覽器窗口完全加載時觸發(fā)。

2.檢查用戶是否離線/在線示例

使用 Navigator.onLine 屬性來檢查用戶是否在線,在 JavaScript 中定義事件處理函數(shù)來處理 Window 對象的離線和在線事件,以監(jiān)控用戶是否斷網(wǎng)。

<!doctype html>
	<head>
		<style>
			body {
			    padding:10px;
			    font-family:arial;
			    font-size:1.2em;
			}
			.error {
			    background-color:#ff5252;
			    color:white;
			    padding:10px;
			    border-radius:5px;
			    margin-top:10px;
			}
			.success {
			    background-color:#00e676;
			    color:white;
			    padding:10px;
			    border-radius:5px;
			    margin-top:10px;
			}
		</style>
		<title>判斷用戶在線或者離線</title>
	</head>
	<body>
		<h2>Welcome to Studytonight!</h2>
        <p>This is a simple code example to show you how to find when a user goes offline and when the user comes back online to show some messages to the user when this hAppens.</p>
        <div id="status"></div>
		<script>
			let status = document.getElementById("status");
            // 監(jiān)聽load事件
            window.addEventListener('load', function(e) {
                if (navigator.onLine) {
                    status.innerHTML = "User is online";
                    status.classList.add("success");
                } else {
                    status.innerHTML = "User is offline";
                    status.classList.remove("success");
                    status.classList.add("error");
                }
            }, false);
            // 監(jiān)聽online事件
            window.addEventListener('online', function(e) {
                status.innerHTML = "User is back online";
                status.classList.remove("error");
                status.classList.add("success");
            }, false);
            // 監(jiān)聽offline事件
            window.addEventListener('offline', function(e) {
                status.innerHTML = "User went offline";
                status.classList.remove("success");
                status.classList.add("error");
            }, false);
		</script>
	</body>
</html>

3.部分瀏覽器hack

值得注意的是,window.navigator.onLine 屬性及其相關(guān)事件目前在某些 Web 瀏覽器(尤其是 Firefox 桌面)上不可靠,下面使用jQuery定期檢查網(wǎng)絡(luò)連接狀態(tài)。

// Global variable somewhere in your app to replicate the 
// window.navigator.onLine variable (this last is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;

function checkNetwork() {
  $.ajax({
    // Empty file in the root of your public vhost
    url: '/networkcheck.txt',
    // We don't need to fetch the content (I think this can lower
    // the server's resources needed to send the HTTP response a bit)
    type: 'HEAD',
    cache: false, 
    // Needed for HEAD HTTP requests
    timeout: 2000,
    // 2 seconds
    success: function() {
      if (!IS_ONLINE) { // If we were offline
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    },
    error: function(jqXHR) {
      if (jqXHR.status == 0 && IS_ONLINE) {
        // We were online and there is no more network connection
        IS_ONLINE = false; // We are now offline
        $(window).trigger('offline'); // Raise the offline event
      } else if (jqXHR.status != 0 && !IS_ONLINE) {
        // All other errors (404, 500, etc) means that the server responded,
        // which means that there are network connectivity
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    }
  });
}

可以通過如下方式進(jìn)行調(diào)用:

// Hack to use the checkNetwork() function only on Firefox 
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
    window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}

使用jQuery監(jiān)聽連接、斷開連接事件:

$(window).bind('online offline', function(e) {
  if (!IS_ONLINE || !window.navigator.onLine) {
    alert('We have a situation here');
  } else {
    alert('Battlestation connected');
  }
});

4.本文總結(jié)

本文主要和大家介紹如何使用JavaScript檢測用戶是否在線,主要是通過window.navigator.onLine屬性和window的online/offline完成。文末的參考資料提供了優(yōu)秀文檔以供學(xué)習(xí),如果有興趣可以自行閱讀。如果大家有什么疑問歡迎在評論區(qū)留言。

 

參考資料

https://www.studytonight.com/post/check-if-user-is-offline-online-in-javascript

https://daily-dev-tips.com/posts/detecting-if-the-user-is-online-with-javascript/

https://medium.com/@codebubb/how-to-detect-if-a-user-is-online-offline-with-javascript-b508fc595f2

https://stackoverflow.com/questions/3181080/how-to-detect-online-offline-event-cross-browser

封面圖:來自iamabhishek的文章,鏈接為:
https://www.studytonight.com/post/check-if-user-is-offline-online-in-javascript

分享到:
標(biāo)簽:JavaScript
用戶無頭像

網(wǎng)友整理

注冊時間:

網(wǎng)站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨大挑戰(zhàn)2018-06-03

數(shù)獨一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運動步數(shù)有氧達(dá)人2018-06-03

記錄運動步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績評定2018-06-03

通用課目體育訓(xùn)練成績評定