線上/離線事件偵測
概述
線上和離線事件偵測可以使用標準 HTML5 API 的一部分 navigator.onLine
屬性,在渲染器進程中實作。線上和離線事件
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。