title: JavaScript check for internet
body: <p>I have a web app that needs to check if the web browser is connected to the internet when the function below is called.</p>
  
  <pre><code>function ping(){
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
          if (this.readyState == 4 &amp;&amp; this.status == 200) {
              // Typical action to be performed when the document is ready:
              console.log("response: " + xhttp.responseText);
          }
      };
      xhttp.open("GET", "http://www.google.com", true);
      xhttp.send();
  }
  </code></pre>
  
  <p>Below are the function results from the google chrome console. It somewhat works...</p>
  
  <p>When connected to the internet:</p>
  
  <blockquote>
    <p>Failed to load <a href="https://www.google.com/" rel="nofollow noreferrer">https://www.google.com/</a>: No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin 'null' is therefore not allowed access.</p>
  </blockquote>
  
  <p>When no internet connection:</p>
  
  <blockquote>
    <p>GET <a href="https://www.google.com/" rel="nofollow noreferrer">https://www.google.com/</a> 0 ()</p>
  </blockquote>
  
  <p>So, if I could differentiate between the errors, there would be my function, but I also have a feeling that this is a completely weird way of doing this. </p>
  
  <p>Is there a better/simpler way of checking for an internet connection?</p>