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

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

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(4)
黄舟

试试navigator.onLine,不需要node.js不需要electron,普通网页都能判断是否有网络

黄舟

官方文档:
http://electron.atom.io/docs/...

天蓬老师
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.

高洛峰

监听navigator.onLine可以实现,感谢两位的帮助

window.addEventListener("offline", function(e) {
    alert("offline")
})
window.addEventListener("online", function(e) {
    alert("online")
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号