最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Redirect to a different page if "webpage not found"? - Stack Overflow

programmeradmin1浏览0评论

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)
    }
});
发布评论

评论列表(0)

  1. 暂无评论