在线/离线事件检测
¥Online/Offline Event Detection
概述
¥Overview
在线和离线事件检测可以在主进程和渲染进程中实现:
¥Online and offline event detection can be implemented in both the main and renderer processes:
-
渲染进程:使用
navigator.onLine属性和 在线/离线事件,它们是标准 HTML5 API 的一部分。¥Renderer process: Use the
navigator.onLineattribute and online/offline events, part of standard HTML5 API. -
主进程:使用
net.isOnline()方法或net.online属性。¥Main process: Use the
net.isOnline()method or thenet.onlineproperty.
navigator.onLine 属性返回:
¥The navigator.onLine attribute returns:
-
false如果所有网络请求都保证失败(例如,当与网络断开连接时)。¥
falseif all network requests are guaranteed to fail (e.g. when disconnected from the network). -
true在所有其他情况下。¥
truein all other cases.
由于许多情况返回 true,因此你应该小心对待误报的情况,因为我们不能总是假设 true 值意味着 Electron 可以访问互联网。例如,当计算机运行虚拟化软件时,该软件的虚拟以太网适配器处于 "始终连接" 状态。因此,如果你想确定 Electron 的互联网访问状态,你应该为此检查开发额外的手段。
¥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.
主进程检测
¥Main Process Detection
在主进程中,你可以使用 net 模块来检测在线/离线状态:
¥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)
net.isOnline() 和 net.online 都返回相同的布尔值,并且与 navigator.onLine 具有相同的可靠性特性。 - false 可以提供离线状态的明确指示,但 true 值并不能保证网络连接成功。
¥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.
net 模块仅在应用发出 ready 事件后可用。
¥[!NOTE]
The net module is only available after the app emits the ready event.
渲染器进程示例
¥Renderer Process Example
从 HTML 文件 index.html 开始,此示例将演示如何使用 navigator.onLine API 构建连接状态指示器。
¥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.
<!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>Connection status: <strong id='status'></strong></h1>
<script src="renderer.js"></script>
</body>
</html>
为了改变 DOM,创建一个 renderer.js 文件,将事件监听器添加到 'online' 和 'offline' window 事件。事件处理程序根据 navigator.onLine 的结果设置 <strong id='status'> 元素的内容。
¥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.
const updateOnlineStatus = () => {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline'
}
window.addEventListener('online', updateOnlineStatus)
window.addEventListener('offline', updateOnlineStatus)
updateOnlineStatus()
最后,为创建窗口的主进程创建一个 main.js 文件。
¥Finally, create a main.js file for main process that creates the window.
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()
}
})
启动 Electron 应用后,你应该会看到通知:
¥After launching the Electron application, you should see the notification:

[!NOTE] 如果你需要在主进程中检查连接状态,可以直接使用
net.isOnline(),而无需通过渲染进程使用 IPC 进行通信。¥[!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.