使用jquery检查互联网是否处于活动状态

时间:2012-07-18 09:03:22

标签: javascript jquery listener internet-connection

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

$(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

感谢。

1 个答案:

答案 0 :(得分:0)

online&amp; offline个事件是HTML5的一部分,因此不适用于旧浏览器。

要支持这些浏览器,您应定期启动hasInternets()(例如,通过setInterval),并相应地回应响应是否成功。

你也可以知道window.navigator.onLine,但请注意incredible amount of browser variations/ bugs;所以这是我试图避免的财产。

相关问题