零零乙 2008-10-09 22:23 采纳率: 33.3%
浏览 402
已采纳

检测互联网连接是离线的吗?

How to detect the Internet connection is offline in JavaScript?

转载于:https://stackoverflow.com/questions/189430/detect-the-internet-connection-is-offline

  • 写回答

16条回答 默认 最新

  • 7*4 2008-10-09 22:28
    关注

    You can determine that the connection is lost by making failed XHR requests.

    The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

    Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.

    Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.

    Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google in this case would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app.. This is a catch-22, because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧