メインコンテンツへ飛ぶ

オンライン/オフライン イベントの検出

概要

Online and offline event detection can be implemented in both the main and renderer processes:

navigator.onLine 属性の戻り値は以下の通りです。

  • false ネットワーク要求が失敗することが保証されている場合、つまり確実にオフラインの (ネットワークから切断されている) 場合。
  • true それ以外の状況。

他のすべての条件で trueが返されるので、true の値は必ずしも Electron がインターネットアクセス可能であるとは限りません。誤検出に注意する必要があります。 例えば、仮想イーサネットアダプタを "常時接続" 状態にした仮想化ソフトをコンピュータ上で実行している場合などです。 したがって、Electron のインターネットアクセス状況を判定したい場合には、さらにこの確認手段を開発する必要があります。

Main Process Detection

In the main process, you can use the net module to detect online/offline status:

const { net } = require('electron')

// Method 1: Using net.isOnline()
const isOnline = net.isOnline()
console.log('Online status:', isOnline)

// Method 2: Using net.online property
console.log('Online status:', net.online)

Both net.isOnline() and net.online return the same boolean value with the same reliability characteristics as navigator.onLine - they provide a strong indicator when offline (false), but a true value doesn't guarantee successful internet connectivity.

[!NOTE] The net module is only available after the app emits the ready event.

Renderer Process Example

このサンプルでは、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ファイルを作成して、そこで window'online''offline' の イベントにイベントリスナーを追加します。 イベントハンドラーでは、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 アプリケーションを起動すると、以下のような通知が表示されるでしょう。

接続状態

[!NOTE] If you need to check the connection status in the main process, you can use net.isOnline() directly instead of communicating from the renderer process via IPC.