How to detect the Internet connection is offline in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- void before promise syntax
- Keeping track of variable instances
There are a number of ways to do this:
You could put an
onerror
in animg
, likeThis 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.
My way.
Almost all major browsers now support the
window.navigator.onLine
property, and the correspondingonline
andoffline
window events:Try setting your system or browser in offline/online mode and check the console or the
window.navigator.onLine
property for the value changes. You can test it on this website as well.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.
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
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.
I think it is very simple way.