How to check if page exists using JavaScript

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/

Leave a Comment