How to Detect Online/Offline Event Cross-Browser

How to detect online/offline event cross-browser?

Currently in 2011, the various browser vendors cannot agree on how to define offline. Some browsers have a Work Offline feature, which they consider separate to a lack of network access, which again is different to internet access. The whole thing is a mess. Some browser vendors update the navigator.onLine flag when actual network access is lost, others don't.

From the spec:

Returns false if the user agent is
definitely offline (disconnected from
the network). Returns true if the user
agent might be online.

The events online and offline are
fired when the value of this attribute
changes.

The navigator.onLine attribute must
return false if the user agent will
not contact the network when the user
follows links or when a script
requests a remote page (or knows that
such an attempt would fail), and must
return true otherwise.

Finally, the spec notes:

This attribute is inherently
unreliable. A computer can be
connected to a network without having
Internet access.

My script for detecting online/offline event is not working. Always shows the user as online

According to MDN page there is no status_online event, but there is however, online event

Another mistake you have is there is no element with id user_status, so you'll need either add an id or use querySelector(".user_status") instead.

Also, you are trying to replace entire className with a single name, which means class name user_status will be removed from the element, but your css is depended on that name.

So in the situations like this, it's probably a better approach to use an attribute instead of class name, this way you don't have to worry about previous "status" class, this especially handy if you have more than 2 conditions.

const user_status = document.getElementById("user_status");

function updateOnlineStatus(event) {
let condition = navigator.onLine ? "online" : "offline";

//dataset is simpliest to use, it automatically adds attribute to the element
user_status.dataset.status = condition;

console.log("Event: " + event.type, " Status: " + condition);
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

updateOnlineStatus({}); //set initial status
/* ---------------------------------- */
/* user status icon
------------------------------------- */
.user_status {
position: absolute;
content: "";
height: 14px;
width: 14px;
background-color: #c0c0c0;
bottom: 0;
right: 0;
display: block;
border: 2.5px solid #fff;
border-radius: 50%;
/* this kind of redundent */
/* visibility: hidden; */
}

.user_status[data-status="online"] {
background-color: #38b653;
visibility: visible;
}

/* ignore this */
.profile_avatar
{
display: inline-block;
position: relative;
}
<div class="profile_avatar">

<div class="profile_avatar_holder">

<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj" alt="Sample Image">

</div>

<div id="user_status" class="user_status"></div>
</div>

Detecting online status of the browser in JavaScript

The Navigator.onLine property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page. For example, the property should return false when users click links soon after they lose internet connection.

Browsers implement this property differently.

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." 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 a true value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connection like Chrome and Safari giving false positives.

Reference:

Navigator.onLine

Detect the Internet connection is offline?

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.

detect change on navigator.online

Something like this (not every browser supports these events, currently only IE 8,9 and FF > 3 support these events):

var el = document.body;
if (el.addEventListener) {
el.addEventListener("online", function () {
alert("online");}, true);
el.addEventListener("offline", function () {
alert("offline");}, true);
}
else if (el.attachEvent) {
el.attachEvent("ononline", function () {
alert("online");});
el.attachEvent("onoffline", function () {
alert("offline");});
}
else {
el.ononline = function () {
alert("online");};
el.onoffline = function () {
alert("offline");};
}

The browser support varies, check this out: http://help.dottoro.com/ljnasgpu.php

Offline event not get fired

After years, I've found a more reliable way to attach an event for connection changes

navigator object has a connection which in turn has an onchange property which expects a callback method to be executed whenever a connection change occurs

navigator.connection.onchange=function()
{
if(navigator.onLine)
{
console.log('Connection is okay')
}
else
{
console.log('Connection lost')
}
}

But...According to MDN, the navigator.onLine could return false positives

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." Therefore, if you really want to
determine the online status of the browser, you should develop
additional means for checking.



Related Topics



Leave a reply



Submit