0

I am trying to check if a URL exists or not. But I am caught by CORS - This is what I tried:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function checkUrl(url){
        var request = new XMLHttpRequest;
        request.open('GET', url, true);
        request.send();
        request.onreadystatechange = function(){
            if(request.readyState==4){
                if(request.status==200){
                    console.log(request.readyState);
                    return true;
                }
            }else{
                return false;
            }
        }
        };

        var url = 'http://localhost:' + 8080 + '/hello/';
        if(checkUrl(url)){
            alert('Success');
        }else{
            alert('Failure');
        }
    </script>
  </head>
  <body>

  </body>
</html>

I am getting the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/hello/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Note: I have a limitation: I wont be able to use any Ajax/jQuery related code.

Please let me know how to resolve this.

user182944
  • 7,897
  • 33
  • 108
  • 174
  • 1
    [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) *is* AJAX. It's what powers jQuery's core `$.ajax`. – Oka Jun 07 '15 at 08:37

2 Answers2

5

You can't.

Browsers won't let arbitrary websites the visit use them to probe other websites.

You can only do this using server side code (which you can use to pass information to the browser via Ajax).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You can load something from the remote site (an image for example) and use the onload handler. Doesn't work full-proof but it's the best you're going to get here.

Wolph
  • 78,177
  • 11
  • 137
  • 148