How to check if page exists using JavaScript

Viewed 95300

I have a link: <a href="http://www.example.com">Hello</a>.

When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.

9 Answers

Based on the documentation for XMLHttpRequest:

function returnStatus(req, status) {
  //console.log(req);
  if(status == 200) {
    console.log("The url is available");
    // send an event
  }
  else {
    console.log("The url returned status code " + status);
    // send a different event
  }
}

function fetchStatus(address) {
 var client = new XMLHttpRequest();
 client.onreadystatechange = function() {
  // in case of network errors this might not give reliable results
  if(this.readyState == 4)
   returnStatus(this, this.status);
 }
 client.open("HEAD", address);
 client.send();
}

fetchStatus("/");

This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.

You won't be able to use an ajax call to ping the website because of same-origin policy. The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.

Example:

function pingImgOnWebsite(url) {
    var img = document.createElement('img');
    img.style.visibility = 'hidden';
    img.style.position = 'fixed';
    img.src = url;
    img.onerror = continueBtn; // What to do on error function
    document.body.appendChild(img);
}
Related