Detect the Internet connection is offline?

后端 未结 19 1370
甜味超标
甜味超标 2020-11-22 00:53

How to detect the Internet connection is offline in JavaScript?

相关标签:
19条回答
  • 2020-11-22 01:52

    I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.

    I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.

    $.ajax({
        url:      'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
        dataType: 'jsonp',
        timeout:  5000,
    
        error: function(xhr) {
            if (xhr.status == 404) {
                //internet connection working
            }
            else {
                //internet is down (xhr.status == 0)
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题