user526206 user526206 - 1 year ago 66
Javascript Question

How to check if URL is available or not using javascript

I am trying to use jQuery to check if URL is available or not. I am using the below Javascript code to verify this but it works for only HTTP URLs. If the URL is HTTPS it fails and I get the error


var backendUrl = "https://myserver:8081/app/test.jsp";
type: "GET",
url: backendUrl
}).done(function (result) {
window.location.href = backendUrl;
}).fail(function () {
alert(Sorry URL is not access able");

Can someone tell me a reason and some more precise way to check if URL is available or not using javascript.

Answer Source

This is what I use to check if a URL exists:

function UrlExists(url, cb){
                url:      url,
                dataType: 'text',
                type:     'GET',
                complete:  function(xhr){
                    if(typeof cb === 'function')
                       cb.apply(this, [xhr.status]);

        UrlExists('-- Insert Url Here --', function(status) {
            if(status === 200) {
                -- Execute code if successful --
            } else if(status === 404) {
                -- Execute code if not successful --
               -- Execute code if status doesn't match above --

There are many status codes so you can change out the 404 to whatever code you want to match or just put the code you want to execute in the last else case and that code will execute if the status does not match any of the requested status codes.