Check Internet Connection


#1

Hey Guys.

I would make an app that loads simply to things.

If User is Online there Shows Google.com and if User are offline there loads a index.html offline file.

here is my code:

var electron = require('electron');
var app = electron.app;
var Menu = electron.Menu;
var BrowserWindow = electron.BrowserWindow;
var openAboutWindow = require('about-window').default;
var join = require('path').join;

app.once('window-all-closed',function() { app.quit(); });

app.once('ready', function() {

    const ElectronOnline = require('electron-online')
    const connection = new ElectronOnline()

    var w = new BrowserWindow({title: 'APP', center: undefined, transparent: true, width: 1024, height: 768, frame: true, resizable: false});
    w.once('closed', function() { w = null; });
    
    connection.on('online', () => {
      w.loadURL('http://google.com')
    })

    connection.on('offline', () => {
      w.loadURL(`file://${__dirname}/index.html`)
    })

    const menu = Menu.buildFromTemplate([
        {
            label: 'About',
            submenu: [
                {
                    label: 'About This App',
                    click: () => openAboutWindow({
                                icon_path: join(__dirname, 'icon.png'),
                                copyright: 'Copyright',
                                open_devtools: false,
                            })
                }
            ]
        }
    ]);
    Menu.setApplicationMenu(menu);
});

But i get some errors if i switch my internet connection.
Hope any1 can help.


#2

I am using below code it is working fine for me.

function check_online_status() {

    if (navigator.onLine) {
        doLogin(authentication_api);
        console.log('User is online  so redirect to login');
    }else{
        console.log('User went to offline or no internet connection');
        alert("It seems you dont have internet connections");
    }
}

Thanks
Jk


#3

navigator.onLine is useless, it only checks if you have a local connection, not whether the internet is accessible.

Use this node module to do the magic!


#4

Thanks for the suggestion.
Will use it my project