gpt4 book ai didi

JavaScript 检测用户是否离线

转载 作者:行者123 更新时间:2023-11-28 06:37:55 25 4
gpt4 key购买 nike

我目前正在开发一个网络应用程序。我正在使用应用程序缓存。所以我想做的实际上非常简单:如果用户在没有互联网连接的情况下加载页面,他会看到一个带有文本“离线”的按钮,否则带有文本“在线”。我的第一个方法是使用offline.js,但它无法正确检测用户何时在线/离线。

所以我尝试了这段代码:

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;
}
}

但是,当通过 AppCache 加载页面时,XHR-Requests 似乎会失败。使用 navigator.onLine 是不可行的,因为我们的大多数用户都使用 Chrome。

有解决办法吗?谢谢

最佳答案

navigator.onLine 确实在 Chrome 中工作。

关于JavaScript 检测用户是否离线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34106427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com