electron/docs-translations/zh-CN/tutorial/online-offline-events.md

76 lines
1.9 KiB
Markdown
Raw Normal View History

# 在线/离线事件探测
使用标准 HTML5 APIs 可以实现在线和离线事件的探测,就像以下例子:
2016-10-03 23:40:51 +00:00
_main.js_
2015-12-19 06:27:47 +00:00
```javascript
2016-10-03 23:40:51 +00:00
const {app, BrowserWindow} = require('electron')
let onlineStatusWindow
2016-10-03 23:40:51 +00:00
app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false })
2016-10-03 22:48:04 +00:00
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`)
})
2015-12-19 06:27:47 +00:00
```
2016-10-03 23:40:51 +00:00
_online-status.html_
2015-12-19 06:27:47 +00:00
```html
<!DOCTYPE html>
<html>
2016-10-03 23:40:51 +00:00
<body>
<script>
const alertOnlineStatus = () => {
window.alert(navigator.onLine ? 'online' : 'offline')
}
window.addEventListener('online', alertOnlineStatus)
window.addEventListener('offline', alertOnlineStatus)
alertOnlineStatus()
</script>
</body>
</html>
2015-12-19 06:27:47 +00:00
```
也会有人想要在主进程也有回应这些事件的实例。然后主进程没有 `navigator` 对象因此不能直接探测在线还是离线。使用 Electron 的进程间通讯工具,事件就可以在主进程被使用,就像下面的例子:
*main.js*
2015-12-19 06:27:47 +00:00
```javascript
const electron = require('electron')
const app = electron.app
const ipcMain = electron.ipcMain
const BrowserWindow = electron.BrowserWindow
var onlineStatusWindow
app.on('ready', function () {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false })
2016-10-03 22:48:04 +00:00
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`)
})
ipcMain.on('online-status-changed', function (event, status) {
console.log(status)
})
2015-12-19 06:27:47 +00:00
```
*online-status.html*
2015-12-19 06:27:47 +00:00
```html
<!DOCTYPE html>
<html>
<body>
<script>
const ipcRenderer = require('electron').ipcRenderer;
var updateOnlineStatus = function() {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();
</script>
</body>
</html>
2015-12-19 06:27:47 +00:00
```