跳到主要內容

線上/離線事件偵測

總覽

線上和離線事件偵測可以使用標準 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 應用程式後,您應該會看到通知

Connection status

注意:如果您需要將連線狀態傳達給主要處理程序,請使用 IPC 渲染器 API。