Detect the Internet connection is offline?

2018-12-31 05:48发布

How to detect the Internet connection is offline in JavaScript?

16条回答
梦寄多情
2楼-- · 2018-12-31 06:11

There are a number of ways to do this:

  • AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuery documentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
  • You could put an onerror in an img, like

    <img src='http://www.example.com/singlepixel.gif' 
          onerror='alert("Connection dead");' />
    

    This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.

So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.

查看更多
浮光初槿花落
3楼-- · 2018-12-31 06:11

My way.

<!-- the file named "tt.jpg" should exist in the same directory -->

<script>
function testConnection(callBack)
{
    document.getElementsByTagName('body')[0].innerHTML +=
        '<img id="testImage" style="display: none;" ' +
        'src="tt.jpg?' + Math.random() + '" ' +
        'onerror="testConnectionCallback(false);" ' +
        'onload="testConnectionCallback(true);">';

    testConnectionCallback = function(result){
        callBack(result);

        var element = document.getElementById('testImage');
        element.parentNode.removeChild(element);
    }    
}
</script>

<!-- usage example -->

<script>
function myCallBack(result)
{
    alert(result);
}
</script>

<a href=# onclick=testConnection(myCallBack);>Am I online?</a>
查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 06:13

Almost all major browsers now support the window.navigator.onLine property, and the corresponding online and offline window events:

window.addEventListener('online', () => console.log('came online'));
window.addEventListener('offline', () => console.log('came offline'));

Try setting your system or browser in offline/online mode and check the console or the window.navigator.onLine property for the value changes. You can test it on this website as well.

Note however this quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.

(emphasis is my own)

This means that if window.navigator.onLine is false (or you get an offline event), you are guaranteed to have no Internet connection.

If it is true however (or you get an online event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.

I initially intended to post this as an update to Grant Wagner's answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 06:14

The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3

查看更多
有味是清欢
6楼-- · 2018-12-31 06:18

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)
        }
    }
});
查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 06:19

I think it is very simple way.

var x = confirm("Are you sure you want to submit?");
if(x){
    if(navigator.onLine == true) {
        return true;
    } else {
        alert('Internet connection is lost');
        return false; 
    }
}
else {
    return false;
}
查看更多
登录 后发表回答