mikehall314 / electron-comlink

An adapter for Electron IPC to allow communication with Comlink
MIT License
8 stars 1 forks source link
comlink electron ipc

Build Status

electron-comlink

An adapter to allow Electron to use Comlink to communicate between the background and renderer processes.

Installation

npm install electron-comlink

Usage

Communicate from the background to the renderer

// In the renderer process
const Comlink = require("comlink");
const {ElectronMessageAdapter} = require("electron-comlink");
const endpoint = new ElectronMessageAdapter(window, electron.ipcRenderer);

const exposed = {
    doSomething() {
        return "Did something in the renderer";
    },
};

Comlink.expose(exposed, endpoint);
// In the background process
const Comlink = require("comlink");
const {ElectronMessageAdapter} = require("electron-comlink");

const win = new BrowserWindow({width: 800, height: 600});
const endpoint = new ElectronMessageAdapter(win, electron.ipcMain);

const link = Comlink.wrap(endpoint);
await link.doSomething(); // Returns "Did something in the renderer"

Communicate from the renderer to the background

// In the background process
const Comlink = require("comlink");
const {ElectronMessageAdapter} = require("electron-comlink");

const win = new BrowserWindow({width: 800, height: 600});
const endpoint = new ElectronMessageAdapter(win, electron.ipcMain);

const exposed = {
    doSomethingElse() {
        return "Did something in the background";
    },
};

Comlink.expose(exposed, endpoint);
// In the renderer process
const Comlink = require("comlink");
const {ElectronMessageAdapter} = require("electron-comlink");
const endpoint = new ElectronMessageAdapter(window, electron.ipcRenderer);

const link = Comlink.wrap(endpoint);
await link.doSomethingElse(); // Returns "Did something in the background"

Gotchas