在线/离线事件检测
概述
在线和离线事件检测可以在渲染器进程中使用 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({
width: 400,
height: 100
})
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。