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
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:
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.
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, check for return http status codes etc
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.
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:
request head in request error