Question

Is there a way to check if a connection is not available and show an alert (or whatever content) before the "webpage not available" browser message appears, or add a redirect to another page if the "webpage is not found"?

Was it helpful?

Solution

You can make a call and check the return status with AJAX. Then based on the status code such as 200,404, you can decide what you want to do. This can be done easier with jQuery.ajax() method if you use jQuery.

With jQuery

$.ajax({
 statusCode: {
  404: function() {
    alert( "page not found" );
  }
 }
});

Pure JS:

function checkUrl(url) {
    var request = false;
    if (window.XMLHttpRequest) {
            request = new XMLHttpRequest;
    } else if (window.ActiveXObject) {
            request = new ActiveXObject("Microsoft.XMLHttp");
    }

    if (request) {
            request.open("GET", url);
            if (request.status == 200) { return true; }
    }

    return false;

}

Resource:

With pure js, https://www.igotitworking.com/problem/view/69/

OTHER TIPS

You would have to check before the page was loaded obviously so you'd something like this should work...

$.ajax({
    type: 'HEAD',
    url: 'http://domainname.com/pagename.php',
    success: function() {
        // no 404 error
    },
    error: function() {
        // error in HEAD (404 etc)
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top