正在使用electron和node.js做桌面应用,需要实时监听是否有网络连接,node或者electron是否可以做到
PHP中文网
PHP中文网 2017-04-17 15:29:00
0
4
437

如标题,实时监听网络情况,如果没有网络情况就会显示脱机,请问node或者electron是否可以做到?求教

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
黄舟

Try navigator.onLine, no node.js is required, no electron is required, ordinary web pages can determine whether there is a network

黄舟

Official documentation:
http://electron.atom.io/docs/...

Peter_Zhu
function isOnline(user_callback){
    /**
     * Show a warning to the user.
     * You can retry in the dialog until a internet connection
     * is active.
     */
    var message = function(){
        const {dialog} = require('electron').remote;

        return dialog.showMessageBox({
            title:"There's no internet",
            message:"No internet available, do you want to try again?",
            type:'warning',
            buttons:["Try again please","I don't want to work anyway"],
            defaultId: 0
        },function(index){
            // if clicked "Try again please"
            if(index == 0){
                execute();
            }
        })
    };

    var execute = function(){
        if(navigator.onLine){
            // Execute action if internet available.
            user_callback();
        }else{
            // Show warning to user
            // And "retry" to connect
            message();
        }
    };

    // Verify for first time
    execute();
}

// Use it, the alert("Hello world"); will be executed only if there's an active internet connection.
isOnline(function(){
    alert("Hello world !");
});

you can check out this blog for details.

小葫芦

Monitoring navigator.onLine can be implemented, thank you for your help

window.addEventListener("offline", function(e) {
    alert("offline")
})
window.addEventListener("online", function(e) {
    alert("online")
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template