온라인/오프라인 이벤트 감지
개요
온라인 및 오프라인 이벤트는 렌더러 프로세스에서 표준 HTML5 API의 일부인 navigator.onLine
속성을 사용해 구현할 수 있다.
navigator.onLine
속성은 다음과 같은 값을 반환한다:
- 모든 네트워크 요청이 실패할 것이 확실한 경우(예: 네트워크 연결이 끊긴 경우)
false
를 반환한다. - 그 외의 모든 경우에는
true
를 반환한다.
많은 경우 true
가 반환되기 때문에, true
값이 항상 Electron이 인터넷에 접근할 수 있다는 의미는 아니라는 점을 유의해야 한다. 예를 들어, 컴퓨터가 가상 이더넷 어댑터를 '항상 연결' 상태로 유지하는 가상화 소프트웨어를 실행 중인 경우가 있다. 따라서 Electron의 인터넷 접근 상태를 정확히 확인하려면 추가적인 검증 방법을 개발해야 한다.
예제
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'
윈도우 이벤트에 이벤트 리스너를 추가한다. 이벤트 핸들러는 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 renderer API를 사용한다.