使用jquery检查internet是否处于活动状态

checking if internet is active using jquery

本文关键字:活动状态 是否 internet jquery 检查 使用      更新时间:2023-10-29

我有以下监听器来检查用户是否有活动的互联网连接:

$(function() {  
$( window ).bind(
        "online offline",
        function( event ){
          console.log("-------------------window bind------------------------------");
            if(hasInternets()){
                console.log("window bind online---------------------------------------------");
                sendAllPendingData();
            }else {
                console.log("window bind offline--------------------------------------------");
            }
        }
        );

});
function hasInternets() {
    console.log("hasInternets: " + window.location.href.split("?")[0] + "?" + Math.random());
    var s = $.ajax({ 
        type: "HEAD",
        url: window.location.href.split("?")[0] + "?" + Math.random(),
        async: false
    }).status;
        console.log("s: " +s);
    //thx http://www.louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/ 
    return s >= 200 && s < 300 || s === 304;
}

它在我的笔记本电脑上运行良好。我不确定它在其他机器和设备上是否正常工作。我对这方面不了解。因此,如果有人能提供建议,我将不胜感激。顺便说一句,在我做研究的时候,我在jquery插件上偶然发现了这个TrueOnline,有人试过吗?http://archive.plugins.jquery.com/project/trueonline

谢谢。

online&offline事件是HTML5的一部分,因此在旧的浏览器上不起作用。

为了支持这些浏览器,您应该定期启动hasInternets()(例如通过setInterval),并根据响应是否成功做出相应响应。

您也可能知道window.navigator.onLine,但请注意浏览器的变化/错误数量之多令人难以置信;所以这是我尽量避免的财产。