Electron

mainProcess和renderProcess的通信方式

异步

render process

1
2
3
4
5
6
7
8
9
const ipc = require('electron').ipcRenderer
const asyncMsgBtn = document.getElementById('async-msg')
asyncMsgBtn.addEventListener('click', function () {
ipc.send('asynchronous-message', 'ping')
})
ipc.on('asynchronous-reply', function (event, arg) {
const message = `Asynchronous message reply: ${arg}`
document.getElementById('async-reply').innerHTML = message
})

main process

1
2
3
4
const ipc = require('electron').ipcMain
ipc.on('asynchronous-message', function (event, arg) {
event.sender.send('asynchronous-reply', 'pong')
})

同步

render process

1
2
3
4
5
6
7
const ipc = require('electron').ipcRenderer
const syncMsgBtn = document.getElementById('sync-msg')
syncMsgBtn.addEventListener('click', function () {
const reply = ipc.sendSync('synchronous-message', 'ping')
const message = `Synchronous message reply: ${reply}`
document.getElementById('sync-reply').innerHTML = message
})

main process

1
2
3
4
const ipc = require('electron').ipcMain
ipc.on('asynchronous-message', function (event, arg) {
event.returnValue = 'pong'
})

close时阻止默认行为会导致应用无法退出,解决办法

1
2
3
4
5
6
7
8
9
10
11
12
13
win2.on('close', function(event) {
if(closeAll) return;
event.preventDefault();
app.mainData.settingWindow.hide();
});
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
// if (process.platform !== 'darwin') {
closeAll=1;
app.quit()
// }
})