28

I have a link: <a href="http://www.example.com">Hello</a>.

When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.

4
  • 9
    Please define "valid". The word can have several meanings.
    – Pekka
    Oct 13, 2010 at 11:12
  • So you want to check if a page exists? And if its not using javascript? With what?
    – Ruel
    Oct 13, 2010 at 12:05
  • 7
    there are no dumb questions, there are just people who hesitate to ask
    – mykhal
    Oct 13, 2010 at 12:25
  • Similar: stackoverflow.com/questions/4282151/…
    – trante
    Mar 29, 2014 at 14:49

9 Answers 9

70

It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).

If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:

$.ajax({
    type: 'HEAD',
    url: 'http://yoursite.com/page.html',
success: function() {
        // page exists
},
error: function() {
        // page does not exist
}
});

See also: http://api.jquery.com/jQuery.ajax/

2
  • 1
    Why should this only be possible intra-domain? Mar 25, 2019 at 9:04
  • 1
    @JensMander, as the answer states, it's due to the same-origin policy that browsers have which prevents cross-domain calls. AFAIK, this policy is to prevent XSS and other security vulnerabilities.
    – Bryan
    Jun 15, 2020 at 5:59
6

Based on the documentation for XMLHttpRequest:

function returnStatus(req, status) {
  //console.log(req);
  if(status == 200) {
    console.log("The url is available");
    // send an event
  }
  else {
    console.log("The url returned status code " + status);
    // send a different event
  }
}

function fetchStatus(address) {
 var client = new XMLHttpRequest();
 client.onreadystatechange = function() {
  // in case of network errors this might not give reliable results
  if(this.readyState == 4)
   returnStatus(this, this.status);
 }
 client.open("HEAD", address);
 client.send();
}

fetchStatus("/");

This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.

6

A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/

From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.

Here's some code that would accept a full URL and use YQL to detect if that page exists:

function isURLReal(fullyQualifiedURL) {
    var URL = encodeURIComponent(fullyQualifiedURL),
        dfd = $.Deferred(),
        checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');

    checkURLPromise
            .done(function(response) {
                // results should be null if the page 404s or the domain doesn't work
                if (response.query.results) { 
                    dfd.resolve(true);
                } else {
                    dfd.reject(false);
                }
            })
            .fail(function() {
                dfd.reject('failed');
            });

    return dfd.promise();
}

// usage
isURLReal('http://google.com')
        .done(function(result) {
            // yes, or request succeded
        })
        .fail(function(result) {
            // no, or request failed
        });

Update August 2nd, 2017

It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.

5
  • 1
    This is a great answer. But you must be aware that for a website with a robots.txt containing "User-agent: * Disallow: /" for example, this method will do to "fail" (as Yahoo API will return null results). To be safer, you have to look at the "http-status-code" key value. Jan 12, 2016 at 14:22
  • @BastienLibersa where can I find "http-status-code"? I didn't find it in the response object
    – jgozal
    Nov 23, 2016 at 4:21
  • It will be part of the "url" object when a query fails. Example: query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22wordpress.com%2Fwp-admin%2F%22&format=json&diagnostics=true&callback= Nov 23, 2016 at 8:45
  • this always return fail
    – reggie
    Jul 20, 2017 at 12:44
  • 1
    @reggie yahoo deprecated some stuff at the beginning of july. Replacing some code now.
    – Parris
    Aug 2, 2017 at 16:25
2

If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.

If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.

2

why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.

2
$.ajax({
        url: "http://something/whatever.docx",
        method: "HEAD",
        statusCode: {
            404: function () {
                alert('not found');
            },
            200: function() {
            alert("foundfile exists");
        }
        }
    });
2
  • This seems to be the only valid solution. Why is it downvoted? May be that the author and I are having the same wrong thought. If possible, maybe someone can elaborate. Mar 25, 2019 at 9:04
  • 1
    It is probably downvoted because the author did not elaborate the code with prose.
    – Alrekr
    Apr 18, 2020 at 22:26
1

If you are happy to use jQuery you could do something like this. When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 
<script type="text/javascript">
<!--

$.fn.checkPageExists = function(defaultUrl){

    $.each(this, function(){

        var $link = $(this);

        $.ajax({
            url: $link.attr("href"),
            error: function(){
                $link.attr("href", defaultUrl);
            }
        });
    });
};

$(document).ready(function(){
    $("a").checkPageExists("default.html");
});
//-->
</script> 
3
  • Making it an onClick event handler would reduce the burden of making all the requests all the time, so it would only check when the user clicks the link (instead of all links always) reducing wait time and traffic
    – Allbite
    Oct 13, 2010 at 14:55
  • 1
    @Allbite You could, but then the user would have to click the link and wait for an ajax request to conclude. If this is slow then the link might just appear broken.
    – Buh Buh
    Oct 13, 2010 at 15:38
  • This is probably a bad solution because it needs to issue many requests on page ready. It would be better to make the check on click, because only one would have to be checked. And if HREF points to external domain all links would get the other page address. Jan 4, 2011 at 7:31
1

You won't be able to use an ajax call to ping the website because of same-origin policy. The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.

Example:

function pingImgOnWebsite(url) {
    var img = document.createElement('img');
    img.style.visibility = 'hidden';
    img.style.position = 'fixed';
    img.src = url;
    img.onerror = continueBtn; // What to do on error function
    document.body.appendChild(img);
}
-6

Another way to do this is is with PHP.

You could add

<?php
if (file_exists('/index.php')) 
{ 
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>

And then

<a href="<?php echo $url; ?>Link</a>
4
  • What if PHP is not running on the OP's webservers? It would be perfectly valid to generate that page using, say, ASP.NET. Oct 13, 2010 at 14:49
  • This was just ONE other way to do it.
    – MadsK
    Oct 14, 2010 at 6:06
  • 6
    The title is clear: how to check... using *JavaScript* - not PHP. Not ASP.NET - JavaScript. The code might be correct, but irrelevant to this question.. Jan 4, 2011 at 14:53
  • 1
    what about node.js o_O haha, I'm sure the person is looking for a front-end approach to solving the problem
    – C. S.
    Dec 20, 2013 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.