如何在Javascript中检测网络丢失? [英] How to Detect Network Loss in Javascript?

查看:68
本文介绍了如何在Javascript中检测网络丢失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络应用程序适用于多种手持设备,如iPad Galaxy标签等。应用程序请求服务器上的图像并在客户端上呈现。

My web application works on multiple handheld devices like iPads Galaxy tabs etc. Application request images from the server and render in on the Clients.

现在问题有时发生这种情况时,网络连接在图像渲染过程中丢失,而不是在设备上显示html无图像图标...

Now the problem is sometimes happens, that network connectivity is lost during the rendering of images, than that time that html no-image icon is shown on the devices...

我想要为了妥善处理这种情况,在网络丢失时,我希望捕获它并向用户显示没有网络连接或其他内容的警报......

我尝试用户 navigator.onLine 事件..但是它不适用于我支持的所有浏览器集,例如mozilla等的5-6版本

I tried to user navigator.onLine event.. but it is not working on all set of browser that I am support like, 5-6 version on mozilla etc.

此外,我的应用程序只能在wifi本地网络上运行...可能连接到互联网<或者不能连接... <这个 navigator.onLine 有效..?

请提供其他更好的方法来做到这一点......

Please provide me any other better way to do this...

推荐答案

您可以向服务器发出一点XHR请求并检查返回状态。

You could do a little XHR request to your server and check for the returned status.

如果是 0 ,这意味着连接丢失

所以,这样的东西可以给你一点实用功能:

So, something like this could give you a little utility function:

function isOnline ( callback ) {
    var xhr = new XMLHttpRequest( )
    xhr.onreadystatechange = function ( ) {
        // Make sure the request is finished
        if ( xhr.readyState === 4 ) {
            // There is the magic
            if ( xhr.status === 0 ) {
                callback( false )
            }
            else {
                callback( true )
            }
        }
    }
    xhr.open( '/some/url' )
    xhr.send( )
}

// Usage example:
isOnline( function ( status ) {
    if ( status ) {
        // You're online
    }
    else {
        // You're not online
    }
} )

PS:我跳过 xhr 对象,但它很容易添加。这更像是为了得到这个想法。

PS: I skipped the IE-compliance part for the xhr object, but it'd be easy to add. This is more to get the idea.

这篇关于如何在Javascript中检测网络丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆