2

Using Javascript or jQuery, how can I check if an external link is available?

An $.ajax() call is not available as it violates SOP (same problem as here). I have read about JSONP, but I would like to know if there is a more straight solution, as I don't want to load any data from the external server; what I need is only to check if it is reachable.


EDIT (answer)

I solved it with the following code:

$.ajax({url: 'http://www.example.com',
        type: 'GET',
        dataType: 'jsonp',
        complete: function(jqXHR, textStatus) {
                console.log(jqXHR.status);  // '200' = url reachable
        },
        timeout: 2000
});

The only problem now is that I get a Parse error, but in any case it can be checked if the external link is working.

Community
  • 1
  • 1
Pablo
  • 2,834
  • 5
  • 25
  • 45
  • It seems to be helpful to you: http://stackoverflow.com/questions/635231/javascript-checking-if-page-is-valid – ParPar Feb 08 '12 at 09:32

3 Answers3

2

You could use YQL to check if a URL is available via its JSONP interface.

YQL Console.

alex
  • 479,566
  • 201
  • 878
  • 984
  • If I understand well, to use YQL I need to make a GET call to an external link like 'http://query.yahooapis.com/...'. This will give me the same problem, as I can't receive external data using Javascript. Maybe I have not understand it well... Am I missing something? – Pablo Feb 08 '12 at 09:29
  • @Pablo Yes, you are. Do some research into JSONP, and use that with the YQL response. – alex Feb 08 '12 at 09:30
  • Finally, I solved it another way, but your answer helped me to know where to start from. – Pablo Feb 09 '12 at 07:28
1

Do you have access to server side languages? You could use AJAX to call a local file which uses something like PHP to check the external address.

If you need help with the PHP part, have a look at http://www.catswhocode.com/blog/amazing-things-to-do-with-php-and-curl

472084
  • 17,666
  • 10
  • 63
  • 81
1

Yes, in browsers that support flash you can use this plugin. It has the same api as native xhr. Further if there is no flash plugin in browsers you still can access the other domain. In some browsers if your target domain response has the following headers there will not be an error.

Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, *

Replace * with appropriate domains.

All above techniques are applicable only if the second domain is under your control. If not then you have to use a proxy as Jleagle said.

Oybek
  • 7,016
  • 5
  • 29
  • 49