Online/Offline Event Detection

Overview

Online and offline event detection can be implemented in the Renderer process using the navigator.onLine attribute, part of standard HTML5 API.

The navigator.onLine attribute returns:

  • false if all network requests are guaranteed to fail (e.g. when disconnected from the network).
  • true in all other cases.

Since many cases return true, you should treat with care situations of getting false positives, as we cannot always assume that true value means that Electron can access the Internet. For example, in cases when the computer is running a virtualization software that has virtual Ethernet adapters in “always connected” state. Therefore, if you want to determine the Internet access status of Electron, you should develop additional means for this check.

Example

Starting with an HTML file index.html, this example will demonstrate how the navigator.onLine API can be used to build a connection status indicator.

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Hello World!</title>
  6. <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  7. </head>
  8. <body>
  9. <h1>Connection status: <strong id='status'></strong></h1>
  10. <script src="renderer.js"></script>
  11. </body>
  12. </html>

In order to mutate the DOM, create a renderer.js file that adds event listeners to the 'online' and 'offline' window events. The event handler sets the content of the <strong id='status'> element depending on the result of navigator.onLine.

renderer.js

  1. const updateOnlineStatus = () => {
  2. document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline'
  3. }
  4. window.addEventListener('online', updateOnlineStatus)
  5. window.addEventListener('offline', updateOnlineStatus)
  6. updateOnlineStatus()

Finally, create a main.js file for main process that creates the window.

main.js

  1. const { app, BrowserWindow } = require('electron')
  2. const createWindow = () => {
  3. const onlineStatusWindow = new BrowserWindow({
  4. width: 400,
  5. height: 100
  6. })
  7. onlineStatusWindow.loadFile('index.html')
  8. }
  9. app.whenReady().then(() => {
  10. createWindow()
  11. app.on('activate', () => {
  12. if (BrowserWindow.getAllWindows().length === 0) {
  13. createWindow()
  14. }
  15. })
  16. })
  17. app.on('window-all-closed', () => {
  18. if (process.platform !== 'darwin') {
  19. app.quit()
  20. }
  21. })

After launching the Electron application, you should see the notification:

Connection status

Note: If you need to communicate the connection status to the main process, use the IPC renderer API.