0

I am trying to check if a url is reachable or not using javascript without using jQuery or the method of loading an image from that url. It would be great if I can get the status code of that url, because all I care about is that status code being 200.

I have tried XMLHttpRequest but I learned that it does not support cross domain calls.

Please help.

Thank you.

Sun
  • 559
  • 2
  • 9
  • 30

3 Answers3

2

It is not possible to get the status code directly in JavaScript without XMLHttpRequest. As pointed out, this is generally only same-domain although, there are two possible cross-domain approaches (not requiring a proxy server) to this I know of:

  1. Certain clients and servers willing to play can use Cross-Origin Resource Sharing and;
  2. There are also flash-based "XHR" solutions.

On the other hand, if all that is cared about is the image thought it could be loaded (which might not be a 200 at all!) it is possible to find this out using an Image element and the onload event. If the onload event doesn't fire in a certain amount of time it can be concluded the request timed out or failed (4xx/5xx). However, this will return a false-positive in case of 302, etc.

Just make sure the browser actually tries to load the Image: some of the more clever ones won't load hidden images, or so I've heard.

Happy coding.

2

I'm not sure about how "cross-browser" this is:

<script src="http://www.google.com" onerror="alert('error')"></script> <!-- Is Fine -->
<script src="http://www.notrealnotrealzz.com" onerror="alert('error')"></script> <!-- Alerts Error -->

And it's obviously a hack, but hopefully it will help.

A more dynamic version:

var el = document.createElement('script');
el.onerror = errorFunction;
el.src = url;
document.body.appendChild(el);
Joe
  • 80,724
  • 18
  • 127
  • 145
1

Create a server side script using a server side language, have this script return the status code. This "proxy" script, will request the URL for you, so that no cross domain requests need to be made.

For an example of a Python response code script, see here: What’s the best way to get an HTTP response code from a URL?

Hope that helps, -Sunjay03

Community
  • 1
  • 1
Sunjay Varma
  • 5,007
  • 6
  • 34
  • 51
  • Thanks for your response, Sunjay The problem is that I do not have access to the server's code. It is external to me "literally". For example, the url could be anything (even http://www.google.com). The bottom line is that I don't have access to the server's code. – Sun Sep 21 '11 at 18:17
  • You do not need access to the server's code. My method of using a proxy allows you to avoid that entirely. – Sunjay Varma Sep 22 '11 at 05:34