在线/离线事件检测
概述
在线和离线事件检测可以在主进程和渲染器进程中实现。
- 渲染器进程:使用
navigator.onLine属性和 online/offline 事件,它们是标准 HTML5 API 的一部分。 - 主进程:使用
net.isOnline()方法或net.online属性。
navigator.onLine 属性返回值
- 当所有网络请求都保证会失败时返回
false(例如,断开网络连接时)。 - 在所有其他情况下返回
true。
由于许多情况返回 true,您应该谨慎处理误报的情况,因为我们不能总是假设 true 值意味着 Electron 可以访问互联网。例如,当计算机运行的虚拟化软件具有处于“始终连接”状态的虚拟以太网适配器时。因此,如果您想确定 Electron 的互联网访问状态,您应该开发额外的手段来进行此检查。
主进程检测
在主进程中,您可以使用 net 模块来检测在线/离线状态。
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 值并不保证成功的互联网连接。
注意
net 模块仅在应用程序发出 ready 事件后才可用。
渲染器进程示例
从一个 HTML 文件 index.html 开始,本示例将演示如何使用 navigator.onLine API 来构建一个连接状态指示器。
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'> 元素的内容。
renderer.js
const updateOnlineStatus = () => {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline'
}
window.addEventListener('online', updateOnlineStatus)
window.addEventListener('offline', updateOnlineStatus)
updateOnlineStatus()
最后,为处理主进程的主进程创建一个 main.js 文件,该文件创建窗口。
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 应用程序后,您应该会看到通知。

注意
如果您需要在主进程中检查连接状态,可以直接使用 net.isOnline(),而不是通过 IPC 从渲染器进程进行通信。