Détection des événements online/offline
Vue d'ensemble
Online and offline event detection can be implemented in both the main and renderer processes:
- Renderer process: Use the
navigator.onLineattribute and online/offline events, part of standard HTML5 API. - Main process: Use the
net.isOnline()method or thenet.onlineproperty.
L'attribut navigator.onLine renvoie :
falsesi toute requête réseau est garantie vouée à l'échec (par exemple, lors de la déconnexion du réseau).truedans tous les autres cas.
Puisque de nombreux cas retournent true, vous devrez traiter avec précaution les cas pouvant être des faux positifs, car la valeur true ne signifie pas toujours qu'Electron puisse accéder à Internet. Par exemple, dans les cas où l'ordinateur exécute un logiciel de virtualisation qui a des adaptateurs Ethernet virtuels avec l'état « toujours connecté ». Par conséquent, si vous voulez déterminer le statut de l'accès à Internet d'Electron, vous devrez mettre en œuvre des moyens supplémentaires de vérification.
Main Process Detection
In the main process, you can use the net module to detect online/offline status:
const { net } = require('electron')
// Method 1: Using net.isOnline()
const isOnline = net.isOnline()
console.log('Online status:', isOnline)
// Method 2: Using net.online property
console.log('Online status:', net.online)
Both net.isOnline() and net.online return the same boolean value with the same reliability characteristics as navigator.onLine - they provide a strong indicator when offline (false), but a true value doesn't guarantee successful internet connectivity.
[!NOTE] The
netmodule is only available after the app emits thereadyevent.
Renderer Process Example
En partant d'un fichier HTML index.html, cet exemple démontrera comment l'API navigator.onLine peut être utilisée pour construire un indicateur d'état de connexion.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Etat de la Connexion : <strong id='status'></strong></h1>
<script src="renderer.js"></script>
</body>
</html>
Pour modifier le DOM, créez un fichier renderer.js qui ajoute des écouteurs pour les événements 'online' et 'offline' de window. Le gestionnaire d’événements détermine le contenu de l’élément dont l' id='status' en fonction du résultat de navigator.onLine.
const updateOnlineStatus = () => {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline'
}
window.addEventListener('online', updateOnlineStatus)
window.addEventListener('offline', updateOnlineStatus)
updateOnlineStatus()
Enfin, créez le fichier main.js pour le processus principal qui va créer la fenêtre.
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
const onlineStatusWindow = new BrowserWindow()
onlineStatusWindow.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
Après avoir lancé l’application Electron, vous verrez la notification:

[!NOTE] If you need to check the connection status in the main process, you can use
net.isOnline()directly instead of communicating from the renderer process via IPC.