0

I want to check if server at URL is responding, then set the text of my < p > tag to 'server is online' or 'server is offline'.

I can make a page on my server that returns for ex. 'success' as a plain text. And if my javascript can catch this message it should write 'server is online', else it should try to connect for maximum 5 or more seconds, then write a message 'server is offline'.

I tried the code from this answer, but it turns offline after 1500 ms.

<body onload="Pinger_ping('google.com')">
...
<p id = "status">Checking server status...</p>
...
<script type="text/javascript">

function Pinger_ping(ip, callback) {

  if(!this.inUse) {

    this.inUse = true;
    this.callback = callback
    this.ip = ip;

    var _that = this;

    this.img = new Image();

        var status=document.getElementById('status');

    this.img.onload = function() {status.innerHTML="online";};
    this.img.onerror = function() {status.innerHTML="online";};

    this.start = new Date().getTime();
    this.img.src = "http://" + ip;
    this.timer = setTimeout(function() {status.innerHTML="offline";}, 1500);

  }
}
</script>
Community
  • 1
  • 1

1 Answers1

1

You may try this solution, here I am using image load event to track the connection status.

(function(win) {
  var _ = {};

  _.win = win;

  _.doc = _.win.document;

  _.status = _.doc.createElement('div');
  _.status.className = "hide";
  _.status.innerHTML = "You are now offline !";

  _.doc.getElementsByTagName('body')[0].appendChild(_.status);

  _.img = new Image();

  _.loop = function() {
    _.win.setTimeout(_.nextSrc, 5000);
  };

  _.onLine = function() {
    _.status.className = "hide"; // hide
    _.loop();
  };

  _.offLine = function() {
    _.status.className = "net-err"; // show
    _.loop();
  };

  _.img.onload = _.onLine;
  _.img.onerror = _.offLine;

  _.nextSrc = function() {
    _.img.src = "https://raw.githubusercontent.com/arvind-web-corner/offline-status/gh-pages/blank.png?" + _.win.Math.random();
  };

  _.loop();
})(window);
* {
  font-family: Calibri, Arial !important;
}
.net-err {
  width: 100%;
  display: block;
  z-index: 999;
  padding: 15px 10px;
  background: rgb(255, 9, 9);
  color: #fff;
  font-weight: bold !important;
  text-align: center;
  position: fixed;
  top: -1px;
  left: -1px;
  border: 1px solid #ddd;
  font-size: 30px;
  opacity: 0.9;
  filter: alpha(opacity=90);
  /* IE */
}
.hide {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
  <title>Status</title>
</head>

<body>
  <h1>This page will be tracking your internet connection</h1>
  <h2>You will be notified when you loose connection</h2>
  <h3>e.g. Go to File > Work Offline</h3>
</body>

</html>

script, demo