检测互联网连接是否离线?
如何在 JavaScript 中检测互联网连接是否离线?
How can I detect if the internet connection is offline in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 JavaScript 中检测互联网连接是否离线?
How can I detect if the internet connection is offline in JavaScript?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(24)
我必须为经常与学校合作的客户制作一个网络应用程序(基于ajax),这些学校的互联网连接通常很差,我使用这个简单的功能来检测是否有连接,效果非常好!
我使用 CodeIgniter 和 Jquery:
I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!
I use CodeIgniter and Jquery:
我认为这是一个非常简单的方法。
I think it is a very simple way.
像
navigator.onLine
这样的方法的问题是它们与某些浏览器和移动版本不兼容,对我帮助很大的一个选项是使用经典的XMLHttpRequest
方法并且还预见到文件存储在缓存中的可能情况,响应XMLHttpRequest.status
大于 200 且小于 304。这是我的代码:
The problem of some methods like
navigator.onLine
is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classicXMLHttpRequest
method and also foresee the possible case that the file was stored in cache with responseXMLHttpRequest.status
is greater than 200 and less than 304.Here is my code:
我正在寻找一种客户端解决方案来检测互联网是否已关闭或我的服务器是否已关闭。 我发现的其他解决方案似乎总是依赖于第三方脚本文件或图像,对我来说,这似乎经不起时间的考验。 外部托管脚本或图像将来可能会发生变化并导致检测代码失败。
我找到了一种通过查找带有 404 代码的 xhrStatus 来检测它的方法。 另外,我使用JSONP来绕过CORS限制。 404 以外的状态代码表明互联网连接无法正常工作。
I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.
I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.
如何使用 no-cors 向 google.com 发送不透明的 http 请求?
设置 no-cors 的原因是,即使在我的电脑上禁用网络连接,我也会收到 cors 错误。 所以无论有没有互联网连接,我都会被阻止。 添加 no-cors 会使请求变得不透明,这看起来似乎绕过了 cors,并允许我简单地检查是否可以连接到 Google。
仅供参考:我在这里使用 fetch 来发出 http 请求。
https://www.npmjs.com/package/fetch
How about sending an opaque http request to google.com with no-cors?
The reason for setting no-cors is that I was receiving cors errors even when disbaling the network connection on my pc. So I was getting cors blocked with or without an internet connection. Adding the no-cors makes the request opaque which apperantly seems to bypass cors and allows me to just simply check if I can connect to Google.
FYI: Im using fetch here for making the http request.
https://www.npmjs.com/package/fetch
我的方式。
My way.
现代打字稿方法:
如果您的请求失败,并且
navigator.onLine
为 FALSE,您可以放心,您实际上处于离线状态。如果请求成功,请放心,您实际上已在线。
根据您想要的用户体验,您可能根本不需要太多。
modern typescript approach:
If you have a request fail, and
navigator.onLine
is FALSE, you can rest assured, you are actually offline.If a request succeeds, rest assured, you are effectively online.
Depending on your desired user experience, you may not need much here at all.
只需使用
navigator.onLine
如果这是true
那么你就在线,否则离线Just use
navigator.onLine
if this istrue
then you're online else offline请求错误中的请求头
request head in request error
您可以尝试如果网络连接,这将返回 true
You can try this will return true if network connected
是的,您可以使用浏览器导航器 API 检查网络可用性。
Yes you can check network avilability, by using the browser navigator api.
这是我拥有的辅助实用程序的片段。 这是命名空间的 javascript:
您应该将其与方法检测一起使用,否则会触发“替代”方法来执行此操作。 时间很快就到了,这就是所需要的一切。 其他方法都是 hack。
Here is a snippet of a helper utility I have. This is namespaced javascript:
You should use this with method detection else fire off an 'alternative' way of doing this. The time is fast approaching when this will be all that is needed. The other methods are hacks.
对于两种不同的情况,有 2 个答案:-
如果您在网站上使用 JavaScript(即;或任何前端部分)
最简单的方法是:
但是如果你在服务器端使用js(即节点等),你可以通过发出失败的XHR请求来确定连接丢失。
标准方法是重试请求几次。 如果没有通过,则提醒用户检查连接,然后优雅地失败。
There are 2 answers forthis for two different senarios:-
If you are using JavaScript on a website(i.e; or any front-end part)
The simplest way to do it is:
But if you're using js on server side(i.e; node etc.), 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.
几乎所有主流浏览器现在都支持
window.navigator.onLine
属性,以及相应的online
和offline
窗口事件。 运行以下代码片段进行测试:尝试将系统或浏览器设置为离线/在线模式,并检查日志或
window.navigator.onLine
属性以了解值更改。但请注意 Mozilla 文档 中的引用:
(强调是我自己的)
这意味着如果
window.navigator.onLine
为false
(或者您收到offline
事件),则保证您没有互联网连接。但是,如果它是
true
(或者您收到online
事件),则最多仅意味着系统已连接到某个网络。 例如,这并不意味着您可以访问互联网。 要检查这一点,您仍然需要使用其他答案中描述的解决方案之一。我最初打算将其作为格兰特瓦格纳的答案的更新发布,但它似乎编辑太多了,特别是考虑到 2014 年的更新已经不是来自他。
Almost all major browsers now support the
window.navigator.onLine
property, and the correspondingonline
andoffline
window events. Run the following code snippet to test it:Try setting your system or browser in offline/online mode and check the log or the
window.navigator.onLine
property for the value changes.Note however this quote from Mozilla Documentation:
(emphasis is my own)
This means that if
window.navigator.onLine
isfalse
(or you get anoffline
event), you are guaranteed to have no Internet connection.If it is
true
however (or you get anonline
event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.I initially intended to post this as an update to Grant Wagner's answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.
您可以通过发出失败的 XHR 请求来确定连接是否丢失。
标准方法是重试请求几次。 如果未通过,提醒用户检查连接,然后优雅地失败。
旁注:将整个应用程序置于“离线”状态可能会导致处理状态的大量容易出错的工作。无线连接可能会来来去去等。所以你最好的选择可能是优雅地失败,保留数据,并提醒用户......允许他们最终解决连接问题(如果有),并在相当宽恕的情况下继续使用您的应用程序。
旁注:您可以检查像谷歌这样的可靠网站的连接性,但这可能并不完全有用,因为只是尝试提出您自己的请求,因为虽然谷歌可能可用,但您自己的应用程序可能不可用,而且您仍然需要处理自己的连接问题。 尝试向 google 发送 ping 是确认互联网连接本身已关闭的好方法,因此如果该信息对您有用,那么可能值得麻烦。
旁注:发送 Ping 可以通过与发出任何类型的双向 ajax 请求相同的方式来实现,但发送 ping 到 google,在本例中,会带来一些挑战。 首先,我们会遇到 Ajax 通信中通常遇到的相同跨域问题。 一种选择是设置服务器端代理,其中我们实际上
ping
google(或任何网站),并将 ping 结果返回到应用程序。 这是一个第 22 条规则,因为如果互联网连接确实是问题所在,我们将无法访问服务器,而如果连接问题仅出现在我们自己的域上,我们将无法访问服务器无法区分。 可以尝试其他跨域技术,例如,在页面中嵌入一个指向 google.com 的 iframe,然后轮询 iframe 是否成功/失败(检查内容等)。 嵌入图像可能并不能真正告诉我们任何信息,因为我们需要通信机制的有用响应才能对正在发生的事情得出一个好的结论。 再说一次,确定整个互联网连接的状态可能比其价值更麻烦。 您必须针对您的特定应用程序权衡这些选项。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.IE 8 将支持 window.navigator。 onLine 属性。
但当然这对其他浏览器或操作系统没有帮助。 鉴于了解 Ajax 应用程序中在线/离线状态的重要性,我预测其他浏览器供应商也将决定提供该属性。
在此之前,XHR 或
Image()
或请求都可以提供接近您想要的功能的内容。
更新 (2014/11/16)
主要浏览器现在支持此属性,但您的结果会有所不同。
引自 Mozilla 文档:
IE 8 will support the window.navigator.onLine property.
But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.
Until that happens, either XHR or an
Image()
or<img>
request can provide something close to the functionality you want.Update (2014/11/16)
Major browsers now support this property, but your results will vary.
Quote from Mozilla Documentation:
请参阅
onLine
基本用法See
onLine
Basic usage有多种方法可以做到这一点:
onerror
放入img
中,例如>
。如果源图像被移动/重命名,此方法也可能会失败,并且通常是不如 ajax 选项的选择。
因此,有几种不同的方法来尝试检测这一点,虽然没有完美的方法,但在缺乏跳出浏览器沙箱并直接访问用户网络连接状态的能力的情况下,它们似乎是最好的选择。
There are a number of ways to do this:
onerror
in animg
, like<img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');" />
.This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.
So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.
正如 olliej 所说,使用
navigator.onLine
浏览器属性比发送网络请求更好,因此 developer.mozilla.org/En/Online_and_offline_events,甚至老版本的Firefox和IE也支持。最近,WHATWG 指定添加
online
和offline
事件,以防您需要对navigator.onLine
更改做出反应。另请注意 Daniel Silveira 发布的链接,该链接指出依赖这些信号/属性与服务器同步并不总是一个好主意。
As olliej said, using the
navigator.onLine
browser property is preferable than sending network requests and, accordingly with developer.mozilla.org/En/Online_and_offline_events, it is even supported by old versions of Firefox and IE.Recently, the WHATWG has specified the addition of the
online
andoffline
events, in case you need to react onnavigator.onLine
changes.Please also pay attention to the link posted by Daniel Silveira which points out that relying on those signal/property for syncing with the server is not always a good idea.
是您要寻找的内容,但这里需要添加一些内容,首先,如果您想要继续检查应用程序上的某些内容(例如查看用户是否突然离线,这在大多数情况下是正确的,那么您还需要侦听更改),为此,您向窗口添加事件侦听器以检测任何更改,为了检查用户是否离线,您可以执行以下操作:
并检查是否在线:
is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:
and for checking if online:
您可以使用 $.ajax() 的
error
回调,如果请求失败则触发。 如果textStatus
等于字符串“timeout”,则可能意味着连接已损坏:来自 文档:
,例如:
You can use $.ajax()'s
error
callback, which fires if the request fails. IftextStatus
equals the string "timeout" it probably means connection is broken:From the doc:
So for example:
HTML5 应用程序缓存 API 指定 navigator.onLine,目前可在 IE8 beta、WebKit(例如 Safari)nightlies 中使用,并且已在 Firefox 3 中受支持
The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3
我知道这个问题已经得到解答,但我想加 10 美分来解释什么是更好的,什么是不好的。
Window.navigator.onLine
我注意到一些答案谈到了这个选项,但他们从未提到任何有关警告的内容。
此选项涉及使用“window.navigator.onLine”这是大多数现代浏览器上可用的浏览器导航器界面下的一个属性。 它实际上不是检查互联网可用性的可行选项,因为首先
它以浏览器为中心
,其次大多数浏览器以不同的方式实现此属性
。上面的陈述只是想让你知道单靠浏览器是无法判断的。 所以基本上这个选项是不可靠的。
向自己的服务器资源发送请求
This involves making HTTP request to your own server resource and if reachable assume internet availability else the user is offline. There are some few caveats to this option.
如果您同意您的服务器始终在线,那么您可以选择此选项。
以下是获取自己资源的简单代码片段:
向第三方服务器资源发送请求
We all know CORS is a thing.
此选项涉及向外部服务器资源发出 HTTP 请求,如果可以访问,则假设互联网可用,否则用户处于离线状态。 对此的主要警告是跨源资源共享,它是一种限制。 大多数信誉良好的网站都会阻止 CORS 请求,但对于某些网站,您可以随心所欲。
下面是一个获取外部资源的简单片段,与上面相同,但具有外部资源 url:
因此,最后对于我的个人项目,我选择了第二个选项,其中涉及请求自己的服务器资源,因为基本上有很多因素可以判断是否存在“互联网”用户设备上的“连接”,不仅仅是来自您的网站容器,也不仅仅是来自有限的浏览器 API。
请记住,您的用户也可能处于某些网站或资源被阻止、禁止和无法访问的环境中,这反过来会影响连接检查的逻辑。 最好的选择是:
I know this question has already been answered but i will like to add my 10 cents explaining what's better and what's not.
Window.navigator.onLine
I noticed some answers spoke about this option but they never mentioned anything concerning the caveat.
This option involves the use of "window.navigator.onLine" which is a property under Browser Navigator Interface available on most modern browsers. It is really not a viable option for checking internet availability because firstly
it is browser centric
and secondlymost browsers implement this property differently
.The statements above is simply trying to let you know that browsers alone cannot tell. So basically this option is unreliable.
Sending Request to Own Server Resource
This involves making HTTP request to your own server resource and if reachable assume internet availability else the user is offline. There are some few caveats to this option.
If you agree your server is always online then you can go with this option.
Here is a simple snippet to fetch own resource:
Sending Request to Third-Party Server Resource
We all know CORS is a thing.
This option involves making HTTP request to an external server resource and if reachable assume internet availability else the user is offline. The major caveat to this is the Cross-origin resource sharing which act as a limitation. Most reputable websites blocks CORS requests but for some you can have your way.
Below a simple snippet to fetch external resource, same as above but with external resource url:
So, Finally for my personal project i went with the 2nd option which involves requesting own server resource because basically there are many factors to tell if there is "Internet Connection" on a user's device, not just from your website container alone nor from a limited browser api.
Remember your users can also be in an environment where some websites or resources are blocked, prohibited and not accessible which in turn affects the logic of connectivity check. The best bet will be:
对您的域进行 ajax 调用是检测您是否离线的最简单方法,
这只是为了给您提供概念,它应该得到改进。
例如 error=404 应该仍然意味着你在线
an ajax call to your domain is the easiest way to detect if you are offline
this is just to give you the concept, it should be improved.
E.g. error=404 should still mean that you online