Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh a webpage if internet is available

I need some conditional jquery to check internet availability as below and if available it refresh the page and then wait for same amount of time as of refresh and do the same activity again like in while loop

<script>
var a=navigator.onLine;
 if(a){
    <META HTTP-EQUIV="refresh" CONTENT="10">
 }else{
  alert('ofline');
 }
</script>

Please help regarding above lines of code.

Thank you

like image 536
Noman Uddin Avatar asked Dec 02 '25 14:12

Noman Uddin


1 Answers

One way to check for connectivity would be to set up a small png image or file on your same web server (same domain as current page) and test if you can connect to that file. Setting a timeout on an ajax call will trigger its error handler if no response is received after a number of seconds.

function check_connect()

    var testURL = "/somefile.png"
    var waitTime = 15000  // recheck every 15 seconds

    $.ajax({
      type: 'GET',
      url: testURL,
      timeout: 5000,  // allow this many milisecs for network connect to succeed
      success: function(data) {
        // we have a connection, reload page then try again after waitTime
        location.reload();  // reloads entire page
        window.setTimeout(check_connect, waitTime)  // try again after waitTime miliseconds
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // no connection, try again after waitTime
        window.setTimeout(check_connect, waitTime) 
      }
      });

There may be other helpful answers here JQuery Ajax - How to Detect Network Connection error when making Ajax call

And more about jquery's ajax settings such as timeout are here http://api.jquery.com/jquery.ajax/

like image 161
brobas Avatar answered Dec 05 '25 07:12

brobas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!