Electron-学习笔记(4)

141 阅读1分钟

1. 键盘快捷键

该功能可以为 Electron 应用程序配置应用和全局键盘快捷键。

本地快捷键示例代码:

//为了配置本地快捷键,你需要在创建Menu模块中的MenuItem时指定`accelerator<0>属性

const { Menu, MenuItem } = require('electron');

const menu = new Menu();

menu.append(new MenuItem({ 

 label: 'Electron', 

 submenu: [{ 

 role: 'help', 
 
 //对于MacOS,是 `Alt+Cmd+I`,而对于Linux 和 Windows,则是 `Alt+Shift+I`.

 accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I', 

 click: () => { console.log('Electron rocks!') } 

}] 

}))

全局快捷键示例代码:

//使用globalShortcon模块来检测键盘事件,即使应用程序没有获得键盘焦点。
 
const { app, globalShortcut } = require('electron')

app.whenReady().then(() => {

globalShortcut.register('Alt+CommandOrControl+I', () => {

console.log('Electron loves global shortcuts!')

})

}).then(createWindow)

在浏览器窗口内的快捷方式示例代码:

 function handleKeyPress(event) {
 
 // 你可以把处理按键按下事件的代码放在这里。

  document.getElementById("last-keypress").innerText = event.key;

  console.log(`你按下了 ${event.key}`);

}

window.addEventListener('keyup', handleKeyPress, true)

2.在线/离线事件探测

在渲染进程中,在线/离线事件的探测,是通过标准 HTML5 API 中 navigator.onLine属性来实现的。

navigator.onLine 属性返回值:

  • false:如果所有网络请求都失败(例如,断开网络)。
  • true: 在其他情况下都返回 true

我们在index.html的文件中添加如下代码来检测当前的网络环境

function updateOnlineStatus () {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' :'offline'

}

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

updateOnlineStatus()

同时在我们的main.js中添加如下代码

const { app, BrowserWindow } = require('electron')

function 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 应用程序后,网络在线时可以看到通知:

image.png 网络离线时:

image.png