检查用户是否在线已逐渐成为应用的基础功能,因为大多数网站的用户界面都在不断地与网络服务器通信以进行数据传输,如果用户网络断开,那么应用程序的功能就会受到影响。
因此,本文将看到一些检测用户何时离线以及用户何时重新在线以在网站上显示一些消息来通知用户的方法。
在浏览器对象模型中有 JAVAScript 对象,这些对象在与浏览器交互方面很有用,例如 Window 对象、Navigator 对象、Screen 对象、Document 对象等。本文将使用两个对象,即:Window对象、Navigator对象来判断用户是否断网。
Navigator 对象用于与浏览器进行交互, 可以使用 JavaScript 中的 Navigator 对象获取有关浏览器的所有信息。Navigator 对象的 onLine 属性可用于检查浏览器是否连接到互联网。
if (navigator.onLine) {
console.log('在线');
} else {
console.log('离线');
}
该属性的浏览器支持情况如下:
看起来形式一片大好,整体支持率达到了98.79%,即基本所有的浏览器都已经支持了该属性,包括IE9!
Javascript为Window对象提供了两个连接事件,分别是:
// 离线事件(方式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事件,该事件在浏览器窗口完全加载时触发。
使用 Navigator.onLine 属性来检查用户是否在线,在 JavaScript 中定义事件处理函数来处理 Window 对象的离线和在线事件,以监控用户是否断网。
<!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");
// 监听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);
// 监听online事件
window.addEventListener('online', function(e) {
status.innerHTML = "User is back online";
status.classList.remove("error");
status.classList.add("success");
}, false);
// 监听offline事件
window.addEventListener('offline', function(e) {
status.innerHTML = "User went offline";
status.classList.remove("success");
status.classList.add("error");
}, false);
</script>
</body>
</html>
值得注意的是,window.navigator.onLine 属性及其相关事件目前在某些 Web 浏览器(尤其是 Firefox 桌面)上不可靠,下面使用jQuery定期检查网络连接状态。
// 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
}
}
});
}
可以通过如下方式进行调用:
// 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监听连接、断开连接事件:
$(window).bind('online offline', function(e) {
if (!IS_ONLINE || !window.navigator.onLine) {
alert('We have a situation here');
} else {
alert('Battlestation connected');
}
});
本文主要和大家介绍如何使用JavaScript检测用户是否在线,主要是通过window.navigator.onLine属性和window的online/offline完成。文末的参考资料提供了优秀文档以供学习,如果有兴趣可以自行阅读。如果大家有什么疑问欢迎在评论区留言。
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