在线离线事件探测

使用标准的HTML5API可以在渲染进程中实现在线和离线事件的探测,如下所示

main.js

1
2
3
4
5
6
7
8
9
10
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

let onlineStatusWindow;

app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});

online-status.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
<script>
const alertOnlineStatus = () => {
window.alert(navigator.onLine ? 'online' : 'offline');
};

window.addEventListener('online', alertOnlineStatus);
window.addEventListener('offline', alertOnlineStatus);

alertOnlineStatus();
</script>
</body>
</html>

主进程是没有navigator这个对象的,所以不能直接的探测这些事件,使用Electron的进程间通信
的工具,这些事件将会被传递到主进程,并且根据需要去处理,下面的就是个例子:

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const electron = require('electron');
const app = electron.app;
const ipcMain = electron.ipcMain;
const BrowserWindow = electron.BrowserWindow;

let onlineStatusWindow;

app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});

ipcMain.on('online-status-changed', (event, status) => {
console.log(status);
});

online-status.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<body>
<script>
const {ipcRenderer} = require('electron');
const updateOnlineStatus = () => {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};

window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

updateOnlineStatus();
</script>
</body>
</html>