2

I have a web page that i want it to refresh every 2 minutes, using the following code:

location.reload();

The problem is that I assume that the user is connected; but if it happened that s/he is not connected online the page will fail and give the default browser(no connection error page ); and the page will never refresh except manually by the user

can i include a ping mechanism to decide weather to refresh or not?

stackunderflow
  • 3,811
  • 5
  • 31
  • 43
  • 8
    Fetch the content of the page via AJAX and replace the DOM on success and don't on fail. Or simply do an AJAX ping to your server and on success issue `window.location.reload();` – Klemen Tusar Mar 25 '14 at 10:36
  • Reloading a page every two minutes has to be borderline insain. What user wants to have the page they are viewing reloaded every two minutes, it's like the worst UX ever. There used to be a meta tag for this, and it still works in all browser, but you've probably never even heard about it because everyone and they're grandma stopped using it in 1995. – adeneo Mar 25 '14 at 10:41
  • @techouse i wish you rewrite your comment as an answer so that I accept it as the correct answer :) – stackunderflow Mar 25 '14 at 10:48
  • 1
    Ahh, too late. The boys already worked it out :) – Klemen Tusar Mar 26 '14 at 11:29

4 Answers4

8

You can use navigator.onLine to detect a network connection

setInterval(function() {
    if (navigator.onLine) {
        location.reload();
    }
}, 120000); /* 120000 ~> 2 minutes */

otherwise, you may use instead an HEAD ajax request to a same-domain resource and refresh the page only if the response return a 200/304 status, e.g.

setInterval(function() {

    $.ajax({ 
        url  : "/favicon.ico", /* or other resource */
        type : "HEAD"
    })
    .done(function() {
        location.reload();
    });
}, 120000); /* 120000 ~> 2 minutes */
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

One possibility is to send a query to your server or a very reliable server and check if you get a reply.

The problem with navigator.onLine is that it tells the browser status, but the browser may have an online status while there is no network.

See: Detect Internet Connection as in Gmail Javascript

Community
  • 1
  • 1
Djizeus
  • 4,161
  • 1
  • 24
  • 42
1

You could use the boolean :

if (navigator.onLine) {
    //Actions
}
Brovoker
  • 896
  • 5
  • 16
0

Try this,

var clrInterval=null;
clrInterval = setInterval(function(){
    $.ajax({
       url:'',data:'',
       success:function(data);{
         if(data=='no-success') {
            // your code if no-success
         } else {
            clearInterval(clrInterval);// clear interval if you get success
         }
       }
    });
},5000);
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106