在线/离线事件检测
概述
在线和离线事件检测可以使用 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
的结果设置 <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 应用程序后,您应该看到通知
注意
如果您需要将连接状态传达给主进程,请使用 IPC 渲染器 API。