在线/离线事件检测
概述
在线和离线事件检测可以在渲染进程中使用 navigator.onLine
属性实现,它是标准 HTML5 API 的一部分。
navigator.onLine
属性返回
- 如果所有网络请求都确定会失败(例如,断开网络连接时),则返回
false
。 - 在所有其他情况下返回
true
。
由于许多情况下都返回 true
,因此应谨慎处理误报情况,因为我们不能总是假设 true
值意味着 Electron 可以访问互联网。例如,在计算机运行带有处于“始终连接”状态的虚拟以太网适配器的虚拟化软件时。因此,如果您想确定 Electron 的互联网访问状态,则应为此检查开发额外的手段。
示例
从 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
的结果设置 `` 元素的内容。
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 应用程序后,您应该看到通知
注意:如果您需要将连接状态传达给主进程,请使用 IPC renderer API。