8

如何在Javascript中检查是否有互联网连接?我在 Google 中搜索过,但没有找到解决问题的好方法。

我已经有两个事件处理程序:

document.body.addEventListener("offline", function () {
    //alert("offline")
    masterViewModel.online(false)
}, false);
document.body.addEventListener("online", function () {
    //alert("online")
    masterViewModel.online(true);
}, false);

但是如果我在线,如何检查“onload”功能?

4

4 回答 4

26

在 HTML5 中,根据规范

var online = navigator.onLine;
于 2013-04-16T11:20:13.700 回答
3

嗨,你可以这样做:

var connectionMessage = "internet connection";
var noConnectionMessage = "No internet connection.";
window.onload = checkInternetConnection;
function checkInternetConnection() {
  var isOnLine = navigator.onLine;
   if (isOnLine) {
      alert(connectionMessage);
   } else {
     alert(noConnectionMessage);
   }
}
于 2013-04-16T11:23:32.587 回答
1

var online = navigator.onLine;并非每次都有效。有时您的连接已启用,但即使您在线,您也无法从 Internet 获取数据或无法访问站点...因此在线时间返回 true,因为您在线。那个时间“导航器。在线”不可用。

" 您可能会得到误报,例如计算机运行的虚拟化软件具有始终“连接”的虚拟以太网适配器。因此,如果您真的想确定浏览器的在线状态,您应该开发额外的检查方法。要了解更多信息,请参阅 HTML5 Rocks 文章,“ 检查这篇文章

你必须使用ajax请求来检查......

于 2014-03-15T08:18:14.893 回答
-1

为什么不直接对众所周知的地址进行 ajax 调用,比如 StackOverflow。如果你没有得到 404,你就在线。

于 2017-04-04T17:38:11.567 回答