Javascript 检查是否有internet连接

Javascript 检查是否有internet连接,javascript,dom-events,Javascript,Dom Events,如何在Javascript中检查是否存在internet连接? 我在谷歌上搜索过,但没有找到解决问题的好方法 我已经有两个eventhandler: document.body.addEventListener("offline", function () { //alert("offline") masterViewModel.online(false) }, false); document.body.addEventListener(

如何在Javascript中检查是否存在internet连接? 我在谷歌上搜索过,但没有找到解决问题的好方法

我已经有两个eventhandler:

document.body.addEventListener("offline", function () {
    //alert("offline")
    masterViewModel.online(false)
}, false);
document.body.addEventListener("online", function () {
    //alert("online")
    masterViewModel.online(true);
}, false);
但是如果我在线,如何签入“onload”功能呢?

在HTML5中:


嗨,你可以这样做:

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

var online=navigator.online不是每次都有效。有时您的连接已启用,但即使您联机,也无法从internet获取数据或无法访问网站…因此“联机时间”返回true,因为您联机。此时“navigator.online”不是
可用

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


您必须使用ajax请求来检查……

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

这是浏览器的工作,所以,如果页面正在加载,就让它成为吧,你不是已经在线了吗?嗯,不,你可以从本地服务器甚至从文件系统打开页面。我唯一的建议是创建轻量级ajax请求和超时计数器。如果超时触发,连接可能会断开。检查我喜欢你如何更改两条消息以纠正语法问题XD如果没有internet或服务器关闭,则没有404。404是来自服务器的实际响应,因此,你需要联机才能获得404。4xx响应来自服务器,没有连接时,您将无法获取它们。如果你的目标网站关闭了,你也可能得到假阳性。
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);
   }
}