如何在JavaScript中检测Internet连接是否离线?


当前回答

如何发送一个不透明的http请求到google.com与无cors?

    fetch('https://google.com', {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors',
    }).then((result) => {
        console.log(result)
    }).catch(e => {
        console.error(e)
    })

设置no-cors的原因是,即使在我的pc上取消网络连接时,我也收到了cors错误。所以不管有没有网络连接,我都被封锁了。添加no-cors使请求不透明,这显然似乎绕过cors,并允许我只是简单地检查我是否可以连接到谷歌。

供参考:我在这里使用fetch进行http请求。 https://www.npmjs.com/package/fetch

其他回答

IE 8将支持window.navigator.onLine属性。

但当然,这对其他浏览器或操作系统没有帮助。考虑到了解Ajax应用程序中的在线/离线状态的重要性,我预计其他浏览器供应商也将决定提供该属性。

在此之前,XHR或Image()或<img>请求都可以提供接近您想要的功能。

更新(2014/11/16)

大多数浏览器现在都支持这个属性,但结果会有所不同。

引用自Mozilla文档:

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. All other conditions return a true value.

如何发送一个不透明的http请求到google.com与无cors?

    fetch('https://google.com', {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors',
    }).then((result) => {
        console.log(result)
    }).catch(e => {
        console.error(e)
    })

设置no-cors的原因是,即使在我的pc上取消网络连接时,我也收到了cors错误。所以不管有没有网络连接,我都被封锁了。添加no-cors使请求不透明,这显然似乎绕过cors,并允许我只是简单地检查我是否可以连接到谷歌。

供参考:我在这里使用fetch进行http请求。 https://www.npmjs.com/package/fetch

HTML5应用程序缓存API指定导航器。onLine,目前在IE8测试版中可用,WebKit(例如。Safari)的夜间运行,并且已经在Firefox 3中得到支持

我认为这是一个非常简单的方法。

var x = confirm("Are you sure you want to submit?");
if (x) {
  if (navigator.onLine == true) {
    return true;
  }
  alert('Internet connection is lost');
  return false;
}
return false;

我的方式。

<!-- 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>