How to know if the network is (dis)connected?

走远了吗. 提交于 2019-12-04 02:39:58
Amir Raminfar

You should be able to use navigator.onLine. Here is the help page

https://developer.mozilla.org/en/Online_and_offline_events

navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode" by selecting the corresponding menu item (File -> Work Offline in Firefox).

Another solution (as commented by @Neil):

Components.classes["@mozilla.org/observer-service;1"]
    .getService(Components.interfaces.nsIObserverService)
    .addObserver(myF­unction, "network:offline-status-changed", false);
Tom Brito

The best way I found is to use the following javascript code, that behaves like a ping, and make the test with some big websites, and assume that if none of them answers, so the network must be disconnected.

var ping = {};
ping = {
    img:null,
    imgPreload:null,
    timer:null,
    init:function() {
        var sess = new Date();
        var nocache = sess.getTime();
        var imguri = ping.img+"?time="+nocache;
        var ping.imgPreload = new Image();
        ping.imgPreload.onload = function() {
            clearTimeout(ping.timer);
            ping.timer = null;
            alert("Domain is available");
        };
        ping.imgPreload.src = imguri;
        ping.timer = setTimeout("ping.fail_to_ping()",60000);
    },
    fail_to_ping:function() {
        clearTimeout(ping.timer);
        ping.timer = null;
        ping.imgPreload = null;
        alert("Ping to domain failed!");
    }
};

(from http://crynobone.com/ci/index.php/archive/view/852)

--update

But, as it's not a reliable solution (as you can't rely that the image will be in the website forever), the best solution might be to develop a new XPCom component.

Eh... as per HTML5 (read echmascript 5), the on-/offline events are available.

See it here at Mozilla Hacks

Edit 20/4/2011:
I just encountered an update for this answer, when i was watching a podcast from MS MIX11:
http://channel9.msdn.com/Events/MIX/MIX11/HTM14 around time 43:36, the lecturer is actually talking about the window.navigator.onLine property, where he uses it for detecting if the browser (and the computer) is online. Then he uses the online event to do something when he gets online again.

This method is only available in modern browsers, however. So IE 8 and below have to poll for the connection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!