1

I want to validate a url address actually returns a valid page.

There are two approaches one could take.

  • IFrame - create and iframe that points to the url
  • Ajax - create an ajax request to the url and look at the status codes - Here is some fiddling

The Ajax method is not working because it always returns a status code of 0 for cross domain requests whether the page is there or not.

The IFrame method is not working b.c. I can not find a mechanism for capturing status or errors of the frame.

Most of the google hits I'm getting are for syntax checking.

Fiddle Code for Ajax

var urlTest = function (url) {
    var xhr = new window.XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function () {
        console.log('readyState | status : ' + this.readyState + ' | ' + this.status);
        if (this.readyState === 4) {
            if (this.status === 200) {
                // console.log('4 | 200');
                // xhr.responseText;
            }
        }
    };
    xhr.send(null);
}
urlTest('http://www.google.com'); // cross domain always give status 0
  • The proper way to "check" is to use a HEAD request, not GET. And as you've found, you can't do it from JavaScript, if on a different domain. Send a GET request to your server, then let your server make a HEAD request (or something similar, like `curl`, that checks) – Ian May 09 '13 at 14:43
  • Can I use an ajax HEAD - http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax –  May 09 '13 at 14:48
  • You could run a PHP proxy and use an AJAX request to that to perform the check. – Barmar May 09 '13 at 14:51
  • @Barmar, Ian - so cross-domain is still an issue with HEAD? I have to go through the server either way? –  May 09 '13 at 14:53
  • Like I said, you won't be able to make a cross-domain AJAX request. Of course, you can use JSONP/CORS but those seem a little unnecessary. Just use your server – Ian May 09 '13 at 14:55
  • This jQuery forum thread shows that HEAD fails cross-domain: http://forum.jquery.com/topic/ajax-type-head-and-cross-domain-to-check-file-existence – Barmar May 09 '13 at 14:56
  • @pure_code.com HEAD requests are no different from GET (other than what they actually do), so yes, they have the same "issues" – Ian May 09 '13 at 14:58

1 Answers1

0

You may circumvent the CORS restrictions imposed on browsers by means of a proxy as suggested here (without jsonp):

https://en.m.wikipedia.org/wiki/JSONP