Gibbs
Gibbs

Reputation: 22974

Checking internet connection using JavaScript

PROBLEM

I want to show an alert if WiFi is off [i.e. no internet connection]. In my web page, I have a number of buttons, pop-ups etc. User can click anything when offline. But I want to show if there is a failure in API call. I can check navigator.onLine in each click. But I dont want to write number of function calls or lines. Is there any way to do it commonly using jQuery, JS, Ajax?

"ALERT should be shown when call fails which caused by an user action"

Like $.ajax with error. It shouldn't be bounded with any div/page.

Hi, I have tried the following:

navigator.onLine  // It works fine

I used the below one as mentioned. But it's not working.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>     

Links I have referred

Detect that the Internet connection is offline?

Check Internet connectivity with jquery

and a few more.

Any suggestions?

Upvotes: 2

Views: 2582

Answers (3)

G. Goncharov
G. Goncharov

Reputation: 302

I found the easiest way to check if connection to YouTube (for example) exists - to load some javascript lib from that site and check if it was loaded correctly:

Async loading of example lib (may be in script tag in your document):

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

That script is less than 1kB. When you need to check it in your javascript, use the following:

if (window.YT) 
   ...

Upvotes: 0

Raed Salah
Raed Salah

Reputation: 146

navigator.online checks if there is a network and don't check for internet. If you are connected to a network with no internet it will still return true

You can check using an ajax request to your domain

setInterval(function() {
  $.ajax({
    type: "HEAD",
    url: document.location.pathname + "?param=" + new Date(),
    error: function() {
      console.log(false);
    },
    success: function() {
      console.log(true);
    }
  });
}, 1000);

Upvotes: 2

Ralph
Ralph

Reputation: 305

You may use the native setInterval function here. For instance, inside your document.ready function, or perhaps somewhere else that gets loaded early when the page loads, use a set interval:

setInterval(callbackFunction:,1000/*<--run function every interval in ms*/);

and write your callback funciton (probably above the setInteraval) something like:

var callbackFunction = function(){
  if (navigator.online){
    //manipulate the DOM 
  }
};

Remember to put this in a document.ready() function if you manipulate the DOM, and also that the callback function, if defined outside of the setInterval() invocation, should probably be declared first.

Upvotes: 1

Related Questions