admin管理员组

文章数量:1391937

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"?

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"?

Share Improve this question asked Feb 3, 2014 at 4:21 Matt W.Matt W. 842 silver badges9 bronze badges 2
  • Do you have some source code to provide? – tomirons Commented Feb 3, 2014 at 4:22
  • If you have a webserver like apache this can be configured in the config file. – pawinder gupta Commented Feb 3, 2014 at 4:27
Add a ment  | 

2 Answers 2

Reset to default 4

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./problem/view/69/

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./pagename.php',
    success: function() {
        // no 404 error
    },
    error: function() {
        // error in HEAD (404 etc)
    }
});

本文标签: javascriptRedirect to a different page if quotwebpage not foundquotStack Overflow