conaticus
conaticus

Reputation: 461

Send IPC message from main process to renderer process Electron

Currently I have an Electron menu with a save button on it. When this save button is pressed I wish to send an event to the renderer process, for the renderer to handle the event.

Here is what I have attempted:

Menu Source

const menuTemplate = [
    {
        label: "File",
        submenu: [
            {
                label: "Save",
                accelerator: "Ctrl+S",
                click: () => {
                    BrowserWindow.getFocusedWindow().webContents.send("save");
                }
            },
        ]
    },
]

Renderer Source

ipc.on("save", () => {
    console.log("save");
})

Preload source

import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("ipc", { on: ipcRenderer.on });

When trying this I get no output whatsoever when pressing the save button, including no errors. I can confirm that the correct menu is being utilised by Electron and that the click() function is executing. I can also confirm that ipc.on is indeed defined in the renderer.

How can I get this working? Thanks in advance.

Upvotes: 0

Views: 1380

Answers (1)

skara9
skara9

Reputation: 4194

Try setting the this manually in the on function.

contextBridge.exposeInMainWorld("ipc", { on: ipcRenderer.on.bind(ipcRenderer) });

or make a new function that passes the args:

contextBridge.exposeInMainWorld("ipc", { on(event, fn) { ipcRenderer.on(event, fn) } });

Upvotes: 1

Related Questions