跳转至

Online/Offline Event Detection

概述

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

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 值并不能保证互联网连接一定成功。

[!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' 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 应用后,您应该会看到如下通知:

Connection status

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

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron