繁体   English   中英

检查是否有互联网连接

[英]Check if there is an internet connection

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

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

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 online = navigator.onLine;

嗨,你可以这样做:

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; 不是每次都有效。有时您的连接已启用,但您无法从互联网获取数据或即使您在线也无法访问网站...在线”不可用。

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

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

StackOverflow 说,为什么不直接对一个众所周知的地址进行 ajax 调用。 如果您没有收到 404,则您在线。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM