Reputation: 42543
How can I detect if the internet connection is offline in JavaScript?
Upvotes: 391
Views: 417345
Reputation: 139
Try these two solutions, tested with localhost at http://localhost:63342/PythonScript/Html/HtmlFile.html.
On macOS, it works fine on Chrome and Mozilla Firefox browsers, except Safari
browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online/Offline Example</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.status {
font-size: 24px;
}
.online {
color: green;
}
.offline {
color: red;
}
</style>
</head>
<body>
<div class="status" id="status">Checking connection...</div>
<script>
function updateOnlineStatus() {
const statusElement = document.getElementById('status');
if (navigator.onLine) {
statusElement.textContent = 'You are online!';
statusElement.className = 'status online';
} else {
statusElement.textContent = 'You are offline!';
statusElement.className = 'status offline';
}
}
// Check the initial status
updateOnlineStatus();
// Add event listeners to update status when online or offline status changes
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
</script>
</body>
</html>
On macOS, it works fine on Chrome, Mozilla Firefox and Safari
browsers.
Cross-Origin Resource Sharing (CORS) allows reliable endpoint for this site: https://httpbin.org/get.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Network Check Example</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.status {
font-size: 24px;
}
.online {
color: green;
}
.offline {
color: red;
}
</style>
</head>
<body>
<div class="status" id="status">Checking connection...</div>
<script>
const checkOnlineStatus = async () => {
const statusElement = document.getElementById('status');
try {
const response = await fetch('https://httpbin.org/get', { method: 'GET', cache: 'no-cache' });
if (response.ok) {
statusElement.textContent = 'You are online!';
statusElement.className = 'status online';
} else {
throw new Error('Network response was not ok.');
}
} catch (error) {
console.log('Fetch error:', error);
statusElement.textContent = 'You are offline!';
statusElement.className = 'status offline';
}
};
// Check the initial status
checkOnlineStatus();
// Poll every 5 seconds
setInterval(checkOnlineStatus, 5000);
// Add event listeners to update status when online or offline status changes
window.addEventListener('online', checkOnlineStatus);
window.addEventListener('offline', checkOnlineStatus);
</script>
</body>
</html>
we can handle the fetch promise without async
and await
, using .then()
and .catch()
function checkOnlineStatus() {
const statusElement = document.getElementById('status');
fetch('https://httpbin.org/get', { method: 'HEAD', cache: 'no-cache' })
.then(response => {
if (response.ok) {
statusElement.textContent = 'You are online!';
statusElement.className = 'status online';
} else {
throw new Error('Network response was not ok.');
}
})
.catch(error => {
console.log('Fetch error:', error);
statusElement.textContent = 'You are offline!';
statusElement.className = 'status offline';
});
}
checkOnlineStatus();
Upvotes: 1
Reputation: 361
Yes you can check network avilability, by using the browser navigator api.
const isNetwork = navigator.onLine;
// navigator.onLine will return true/false based on your network condition
console.log(isNetwork)
Upvotes: -2
Reputation: 25267
modern typescript approach:
/**
* @example
* const isOnline = await isGoogleOnline();
*/
async function isGoogleOnline(): Promise<boolean> {
return new Promise((resolve, reject) => {
// approach taken from https://github.com/HubSpot/offline/blob/master/js/offline.js#L223
const img = document.createElement('img');
img.onerror = () => {
// calling `reject` basically means `throw` if using `await`.
// Instead, we'll just resovle with `false`. (https://www.swyx.io/errors-not-exceptions)
resolve(false);
};
img.onload = () => {
resolve(true);
};
img.src = 'https://www.google.com/favicon.ico?_=' + ((new Date()).getTime());
});
}
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.
Upvotes: 3
Reputation: 3731
if (navigator.onLine) {
alert('online');
} else {
alert('offline');
}
Upvotes: 47
Reputation: 1179
How about sending an opaque http request to google.com with no-cors?
fetch('https://google.com', {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors',
}).then((result) => {
console.log(result)
}).catch(e => {
console.error(e)
})
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
Upvotes: 4
Reputation:
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
and offline
events, in case you need to react on navigator.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.
Upvotes: 17
Reputation: 20560
Almost all major browsers now support the window.navigator.onLine
property, and the corresponding online
and offline
window events. Run the following code snippet to test it:
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:
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:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return
true
. So while you can assume that the browser is offline when it returns afalse
value, you cannot assume that atrue
value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.In Firefox and Internet Explorer, switching the browser to offline mode sends a
false
value. Until Firefox 41, all other conditions return atrue
value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.
(emphasis is my own)
This means that if window.navigator.onLine
is false
(or you get an offline
event), you are guaranteed to have no Internet connection.
If it is true
however (or you get an online
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.
Upvotes: 283
Reputation: 151
You can try this will return true if network connected
function isInternetConnected(){return navigator.onLine;}
Upvotes: -2
Reputation: 508
Just use navigator.onLine
if this is true
then you're online else offline
Upvotes: 0
Reputation: 41886
There are a number of ways to do this:
onerror
in an img
, 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.
Upvotes: 40
Reputation: 4658
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.
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 secondly most browsers implement this property differently
.
In Firefox: The property returns a boolean value, with
true
meaning online andfalse
meaning offline but the caveat here is that "the value is only updated when the user follows links or when a script requests a remote page.
" Hence if the user goes offline and you query the property from a js function or script, the property will always returntrue
until the user follows a link.In Chrome and Safari: If the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected".
The statements above is simply trying to let you know that browsers alone cannot tell. So basically this option is unreliable.
If you agree your server is always online then you can go with this option.
Here is a simple snippet to fetch own resource:
// This fetches your website's favicon, so replace path with favicon url
// Notice the appended date param which helps prevent browser caching.
fetch('/favicon.ico?d='+Date.now())
.then(response => {
if (!response.ok)
throw new Error('Network response was not ok');
// At this point we can safely assume the user has connection to the internet
console.log("Internet connection available");
})
.catch(error => {
// The resource could not be reached
console.log("No Internet connection", error);
});
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:
// Firstly you trigger a resource available from a reputable site
// For demo purpose you can use the favicon from MSN website
// Also notice the appended date param which helps skip browser caching.
fetch('https://static-global-s-msn-com.akamaized.net/hp-neu/sc/2b/a5ea21.ico?d='+Date.now())
.then(response => {
// Check if the response is successful
if (!response.ok)
throw new Error('Network response was not ok');
// At this point we can safely say the user has connection to the internet
console.log("Internet available");
})
.catch(error => {
// The resource could not be reached
console.log("No Internet connection", error);
});
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:
Upvotes: 10
Reputation: 104640
window.navigator.onLine
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:
window.addEventListener("offline",
()=> console.log("No Internet")
);
and for checking if online:
window.addEventListener("online",
()=> console.log("Connected Internet")
);
Upvotes: 12
Reputation: 5947
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 classic XMLHttpRequest
method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status
is greater than 200 and less than 304.
Here is my code:
var xhr = new XMLHttpRequest();
//index.php is in my web
xhr.open('HEAD', 'index.php', true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
//If you use a cache storage manager (service worker), it is likely that the
//index.php file will be available even without internet, so do the following validation
if (xhr.status >= 200 && xhr.status < 304) {
console.log('On line!');
} else {
console.log('Offline :(');
}
}
}
Upvotes: 5
Reputation: 18055
an ajax call to your domain is the easiest way to detect if you are offline
$.ajax({
type: "HEAD",
url: document.location.pathname + "?param=" + new Date(),
error: function() { return false; },
success: function() { return true; }
});
this is just to give you the concept, it should be improved.
E.g. error=404 should still mean that you online
Upvotes: 9
Reputation: 71
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:
function checkOnline() {
setTimeout("doOnlineCheck()", 20000);
}
function doOnlineCheck() {
//if the server can be reached it returns 1, other wise it times out
var submitURL = $("#base_path").val() + "index.php/menu/online";
$.ajax({
url : submitURL,
type : "post",
dataType : "msg",
timeout : 5000,
success : function(msg) {
if(msg==1) {
$("#online").addClass("online");
$("#online").removeClass("offline");
} else {
$("#online").addClass("offline");
$("#online").removeClass("online");
}
checkOnline();
},
error : function() {
$("#online").addClass("offline");
$("#online").removeClass("online");
checkOnline();
}
});
}
Upvotes: 7
Reputation: 983
I think it is a very simple way.
var x = confirm("Are you sure you want to submit?");
if (x) {
if (navigator.onLine == true) {
return true;
}
alert('Internet connection is lost');
return false;
}
return false;
Upvotes: 4
Reputation: 34129
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.
Upvotes: 162
Reputation: 5394
request head in request error
$.ajax({
url: /your_url,
type: "POST or GET",
data: your_data,
success: function(result){
//do stuff
},
error: function(xhr, status, error) {
//detect if user is online and avoid the use of async
$.ajax({
type: "HEAD",
url: document.location.pathname,
error: function() {
//user is offline, do stuff
console.log("you are offline");
}
});
}
});
Upvotes: 0
Reputation: 177
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:
<h2>The Navigator Object</h2>
<p>The onLine property returns true if the browser is online:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
</script>
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.
Upvotes: -2
Reputation: 9395
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.
$.ajax({
url: 'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
dataType: 'jsonp',
timeout: 5000,
error: function(xhr) {
if (xhr.status == 404) {
//internet connection working
}
else {
//internet is down (xhr.status == 0)
}
}
});
Upvotes: 3
Reputation: 25931
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:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return
true
. So while you can assume that the browser is offline when it returns afalse
value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.In Firefox and Internet Explorer, switching the browser to offline mode sends a
false
value. All other conditions return atrue
value.
Upvotes: 60
Reputation: 342625
You can use $.ajax()'s error
callback, which fires if the request fails. If textStatus
equals the string "timeout" it probably means connection is broken:
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
From the doc:
Error: A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event
So for example:
$.ajax({
type: "GET",
url: "keepalive.php",
success: function(msg){
alert("Connection active!")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if(textStatus == 'timeout') {
alert('Connection seems dead!');
}
}
});
Upvotes: 11
Reputation: 29
My way.
<!-- the file named "tt.jpg" should exist in the same directory -->
<script>
function testConnection(callBack)
{
document.getElementsByTagName('body')[0].innerHTML +=
'<img id="testImage" style="display: none;" ' +
'src="tt.jpg?' + Math.random() + '" ' +
'onerror="testConnectionCallback(false);" ' +
'onload="testConnectionCallback(true);">';
testConnectionCallback = function(result){
callBack(result);
var element = document.getElementById('testImage');
element.parentNode.removeChild(element);
}
}
</script>
<!-- usage example -->
<script>
function myCallBack(result)
{
alert(result);
}
</script>
<a href=# onclick=testConnection(myCallBack);>Am I online?</a>
Upvotes: 2
Reputation:
Here is a snippet of a helper utility I have. This is namespaced javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
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.
Upvotes: -3
Reputation: 36763
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
Upvotes: 10