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.

1
  • 1
    XMLHttpRequest is AJAX. It's what powers jQuery's core $.ajax. Commented Jun 7, 2015 at 8:37

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.