Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron online/offline event detection


May 25, 2021 Electron



During the rendering process, Online and offline event detection is achieved by using the navigator.onLine navigator.onLine standard HTML5 API. W hen offline (disconnected from the network), navigator.onLine false in addition to true S ince all other conditions return true you must be alert to information false positives, because true will be able to access the Internet in the case of true. F or example, electron cannot access the Internet when the software is running in a virtual machine that the virtual network adapter is always "connected". Therefore, if you want to ensure that Electron is in real network access, you should develop additional detection methods.

Detection of online and offline events can be achieved using standard HTML5 APIs, as in the following example:

main.js

var app = require('app');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;

app.on('ready', function() {
  onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
  onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html');
});

online-status.html

<!DOCTYPE html>
<html>
  <body>
    <script>
      var alertOnlineStatus = function() {
        window.alert(navigator.onLine ? 'online' : 'offline');
      };

      window.addEventListener('online',  alertOnlineStatus);
      window.addEventListener('offline',  alertOnlineStatus);

      alertOnlineStatus();
    </script>
  </body>
</html>

There will also be instances of people who want to respond to these events in the main process. T hen the main process does not navigator object so it cannot probe directly online or offline. Using Electron's inter-process communication tool, events can be made in the main process, as in the following example:

main.js

var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;

app.on('ready', function() {
  onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
  onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html');
});

ipc.on('online-status-changed', function(event, status) {
  console.log(status);
});

online-status.html

<!DOCTYPE html>
<html>
  <body>
    <script>
      var ipc = require('ipc');
      var updateOnlineStatus = function() {
        ipc.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
      };

      window.addEventListener('online',  updateOnlineStatus);
      window.addEventListener('offline',  updateOnlineStatus);

      updateOnlineStatus();
    </script>
  </body>
</html>

Note: If the computer starts the virtual machine's network card drive, there may be offline detection inaccuracies.