how to refresh page using javascript if connected?

懵懂的女人 提交于 2019-12-24 00:06:42

问题


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?


回答1:


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 */



回答2:


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




回答3:


You could use the boolean :

if (navigator.onLine) {
    //Actions
}



回答4:


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);


来源:https://stackoverflow.com/questions/22631869/how-to-refresh-page-using-javascript-if-connected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!