Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect Network Loss in Javascript?

My web application works on multiple handheld devices like iPads Galaxy tabs etc. Application request images from the server and render in on the Clients.

Now the problem is sometimes happens, that network connectivity is lost during the rendering of images, than that time that html no-image icon is shown on the devices...

I want to handle this situation gracefully, at the time of network loss , I want to capture that and show a alert to user that no network connectivity or something...

I tried to user navigator.onLine event.. but it is not working on all set of browser that I am support like, 5-6 version on mozilla etc.

And also my application will run only on wifi local network... May or may not be connected to internet.. will in that suitation also this navigator.onLine works..?

Please provide me any other better way to do this...

like image 755
Dhruv Bansal Avatar asked Oct 09 '22 01:10

Dhruv Bansal


1 Answers

You could do a little XHR request to your server and check for the returned status.

If it is 0, this means the connection is missing.

So, something like this could give you a little utility function:

function isOnline ( callback ) {
    var xhr = new XMLHttpRequest( )
    xhr.onreadystatechange = function ( ) {
        // Make sure the request is finished
        if ( xhr.readyState === 4 ) {
            // There is the magic
            if ( xhr.status === 0 ) {
                callback( false )
            }
            else {
                callback( true )
            }
        }
    }
    xhr.open( '/some/url' )
    xhr.send( )
}

// Usage example:
isOnline( function ( status ) {
    if ( status ) {
        // You're online
    }
    else {
        // You're not online
    }
} )

PS: I skipped the IE-compliance part for the xhr object, but it'd be easy to add. This is more to get the idea.

like image 68
Florian Margaine Avatar answered Oct 13 '22 16:10

Florian Margaine