2

I'm trying to create an if-file-exists check on a URL.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else xhr = null;
  return xhr;
}

function UrlExists(url) {
  var http = createCORSRequest('HEAD', url);
  http.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
      if (this.status == 404) {
        alert(url + " is NOT available!");
      } else if (this.status != 0) {
        alert(url + " is available!");
      }
    }
  };
  http.send();
}

UrlExists("http://bar.baz");
UrlExists("http://google.com");
</script>
Testing URLs
</body>
</html>

Currently getting a XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. error -- even when its running through Apache HTTPd on Mac OS 10.9.

Can you all help me to get this to work?

bitcycle
  • 7,094
  • 13
  • 64
  • 116

1 Answers1

3

This is a cross origin issue. You have to use proxy. For example, I've used YQL. Try the following:

function isValidURL(url) {
    var encodedURL = encodeURIComponent(url);
    var isValid = false;

    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        isValid = data.query.results != null;
      },
      error: function(){
        isValid = false;
      }
    });

    return isValid;
}

The usage is then trivial:

var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Ohad
  • 204
  • 2
  • 14
  • 2
    Holger, I am not sure my answer is critique or a request for clarification, and I believe it DOES answers the question. The problem described is a Cross Origin thing. My answer overcomes this problem. Why do you state that it does not provide an answer to the question? – Ohad May 12 '14 at 07:14