Skip to main content

在线/离线事件检测

🌐 Online/Offline Event Detection

概述

🌐 Overview

在线和离线事件检测可以在主进程和渲染进程中实现:

🌐 Online and offline event detection can be implemented in both the main and renderer processes:

navigator.onLine 属性返回:

🌐 The navigator.onLine attribute returns:

  • false 如果所有网络请求都保证会失败(例如,当网络断开时)。
  • true 在所有其他情况下。

由于许多情况下会返回 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.

note

net 模块只有在应用触发 ready 事件后才可用。

渲染器进程示例

🌐 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.

index.html
<!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.

renderer.js
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.

main.js
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:

Connection status

note

如果你需要在主进程中检查连接状态,可以直接使用 net.isOnline(),而无需通过渲染进程使用 IPC 通信。