[英]JavaScript detect if user is offline
I'm currently working on a web application. 我目前正在开发Web应用程序。 I'm using Appcache.
我正在使用Appcache。 So what I want to do is actually dead simple: If the user loads the page without an internet connection, he'll see a button with the text "offline", otherwise with the text "online".
因此,我要做的实际上是非常简单的:如果用户在没有Internet连接的情况下加载页面,他将看到带有文本“ offline”的按钮,否则将看到文本“ online”的按钮。 My first approach was to use offline.js, but it wasn't correctly detecting when the user was on/offline.
我的第一种方法是使用offline.js,但无法正确检测用户何时上线/下线。
So I've tried this code: 所以我尝试了这段代码:
function serverReachable() {
// IE vs. standard XHR creation
var x = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP"),
s;
x.open(
// requesting the headers is faster, and just enough
"HEAD",
// append a random string to the current hostname,
// to make sure we're not hitting the cache
"//" + window.location.hostname + "/?rand=" + Math.random(),
// make a synchronous request
false
);
try {
x.send();
s = x.status;
// Make sure the server is reachable
return (s >= 200 && s < 300 || s === 304);
// catch network & other problems
} catch (e) {
return false;
}
}
But it seems, that XHR-Requests will fail when the page is loaded via AppCache. 但是看来,当通过AppCache加载页面时,XHR-Requests将失败。 Using
navigator.onLine
is no option, because most of our users are using Chrome. 不能选择使用
navigator.onLine
,因为我们大多数用户都在使用Chrome。
Is there a solution? 有解决方案吗? Thank you
谢谢
navigator.onLine 确实可以在Chrome中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.