Skip to content

Instantly share code, notes, and snippets.

@superRaytin
Created July 12, 2019 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superRaytin/70ac2d0e1195c845d53193187d9c756b to your computer and use it in GitHub Desktop.
Save superRaytin/70ac2d0e1195c845d53193187d9c756b to your computer and use it in GitHub Desktop.
IPC helper for the main process of Electron
import { ipcMain as ipc, BrowserWindow } from 'electron'
// 向渲染进程发送消息
export function send(channel, ...args) {
const currentWindow = BrowserWindow.getFocusedWindow()
return new Promise((resolve) => {
if (currentWindow) {
currentWindow.webContents.send(channel, ...args)
ipc.once(`${channel}`, (event, count, ...res) => {
resolve({ event, payload: res.length === 1 ? res[0] : res })
})
} else {
resolve(null)
}
})
}
// 向渲染进程发送消息,不需要返回
export function sendWithoutReturn(channel, ...args) {
const allWindows = BrowserWindow.getAllWindows()
const currentWindow = allWindows[0]
if (currentWindow) {
currentWindow.webContents.send(channel, ...args)
}
}
// 监听渲染进程发送过来的消息,并回复
export function on(channel, callback) {
const listener = async function (event, uid, ...args) {
const result = await callback(event, ...args)
if (uid) {
event.sender.send(`${channel}-${uid}`, result)
}
}
ipc.on(channel, listener)
return {
dispose: () => {
ipc.removeListener(channel, listener)
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment