1. The main process communicates with the renderer process via IPC, for example:
1) main process
const { ipcMain } = require('electron')
// Listen for renderer information
ipcMain.on('message'.(event, arg) = > {
console.log('ping')
event.sender.send('message-reply'.'pong') // return subroutine
})
// The main process sends messages to the renderer separately
win.webContents.send('message-reply'.'pong')
ipcMain.handle('perform-action'.(event, ... args) = > {
/ /... Represents renderer operations
})
Copy the code
② Rendering process
const { ipcRenderer } = require('electron')
ipcRenderer.send('message'.'ping') // Send to the main process
ipcRenderer.on('message-reply'.(event, arg) = > {
console.log(arg) // pong
}
Call the main process method in the renderer process
ipcRenderer.invoke('perform-action'. args)Copy the code
2. Use the remote module –> only call the main module in the renderer
Implementation principle: Similar to RMI in Java, the underlying is based on IPC
const{ BrowserWindow ... (Main process API module)} =require('electron').remote
Copy the code
Note: Since electron is based on Node, the modularity of Node is the CommonJS (require) specification, which is different from ESM (import-ES6)
Solution: Use WebPack packaging
Electron shortcut key development
The native method of electron is used here. You can also use a third-party JS library such as MouseTrap.
- Listen for keyboard events in the main process
//1, local shortcut --> Use the Menu module accelerator property must be triggered when the application gets focus
const { Menu, MenuItem } = require('electron') - commnJS specificationconst menu = new Menu()
menu.append(new MenuItem({
label: 'Electron'.submenu: [{
role: 'help'.accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I'.click: () = > { console.log('Electron rocks! ') }
}]
}))
Menu.setApplicationMenu(menu)
//2. Global shortcuts listen for keyboard events and are triggered whether the application gets focus or not
app.on('ready'.function () {
/ / register
globalShortcut.register('CommandOrControl+Alt+K'.function () {
dialog.showMessageBox({
type: 'info'.message: 'success! '.detail: 'You pressed a global registry shortcut binding.'.buttons: ['good']
})
})
})
app.on('will-quit'.function () {
// Unlog all shortcut keys
globalShortcut.unregisterAll()
})
Copy the code
- Listen for keyboard events in the renderer process
//1. Use the browser window to listen to keyboard events
e.g.
window.addEventListener('keyup', doSomething, true)
true, which means that the current listener always receives the keystroke before other listeners to avoid the other listeners calling stopPropagation().// Use the third-party library mouseTrap (recommended)
Copy the code