跳转到主内容

在线/离线事件探测

概览

在线和离线事件探测在主进程和渲染进程内都能实现:

navigator.onLine 属性返回值:

  • false:如果所有网络请求都失败(例如,断开网络)。
  • true: 在其他情况下都返回 true

由于许多情况都会返回 true,你应该小心对待误报的情况, 因为我们不能总是假设 true 值意味着 Electron 可以访问互联网。 例如,当计算机运行的虚拟化软件时,虚拟以太网适配器处于 "always connected" 状态。 因此,如果您想要确定 Electron 的互联网访问状态,您应该为此检查进行额外的开发。

主进程探测

在主进程中,你可以使用 net 模块来探测在线/离线状态:

const { net } = require('electron')

// 方法 1:使用 net.isOnline()
const isOnline = net.isOnline()
console.log('Online status:', isOnline)

// 方法 2:使用 net.online 属性
console.log('Online status:', net.online)

net.isOnline()net.online 返回的都是相同的布尔值,可靠性与 navigator.onLine 相同 - 离线(false)时的指示性较强,但是 true 值并不保证已成功连接上互联网。

note

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' 窗口 中. 事件处理器设置基于 navigator.onLine 的结果到 <strong id='status'> element 的内容中。

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 应用程序后,您应该能看到通知:

连接状态

note

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