comlink-electron-endpoint

1.0.3 • Public • Published

Comlink Electron Endpoint

Makes Electron MessagePortMain enjoyable.

Example

renderer.js

import * as Comlink from "comlink"
import { ipcRenderer } from "electron";
import { electronEndpoint } from "comlink-electron-endpoint/renderer";

async function init() {
  // Create MessagePorts
  const { port1, port2 } = new MessageChannel();

  // Send one end to the main process
  ipcRenderer.postMessage('comlink-port', null, [port1]);

  // create an electronEndpoint from the other end
  const endpoint = electronEndpoint(port2);

  // wrap the endpoint to proxy the remote object
  const obj = Comlink.wrap(endpoint);

  // call functions on remote object
  alert(`Counter: ${await obj.counter}`);
  await obj.inc();
  alert(`Counter: ${await obj.counter}`);
}
init();

main.js

import * as Comlink from 'comlink';
import { ipcMain } from 'electron';
import { electronEndpoint } from 'comlink-electron-endpoint/main';

ipcMain.on('comlink-port', (event) => {
  // object to be exposed to renderer
  const obj = {
    counter: 0,
    inc() {
      this.counter++;
    },
  };

  // When we receive a MessagePort in the main process, it becomes a
  // MessagePortMain.
  const port = event.ports[0];

  // create the endpoint for comlink and expose obj
  const endpoint = electronEndpoint(port);
  Comlink.expose(obj, endpoint);
});

Additional Resources

Comlink API

Electron MessagePortMain Tutorial

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.3
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.3
    1
  • 1.0.2
    0
  • 1.0.1
    0
  • 1.0.0
    0

Package Sidebar

Install

npm i comlink-electron-endpoint

Weekly Downloads

1

Version

1.0.3

License

ISC

Unpacked Size

12.5 kB

Total Files

9

Last publish

Collaborators

  • kgullion