Created
July 12, 2019 03:00
-
-
Save superRaytin/70ac2d0e1195c845d53193187d9c756b to your computer and use it in GitHub Desktop.
IPC helper for the main process of Electron
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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