user3898336
user3898336

Reputation: 83

Broadcasting message from ipcMain in electron

I need to broadcast a message from main process of electron to all renderer processes. There is no send option for ipcMain, only an option to reply to the sender via event.sender.send().

Upvotes: 0

Views: 2104

Answers (3)

malko
malko

Reputation: 2382

To elaborate on @Joshua's answers

in your main.js you can add something like that

const {BrowserWindow, ipcMain} = require("electron")

// list of active windows
const windows = []

// method to create windows in your app
const createWindow = (fileToLoad) => {
    const win = new BrowserWindow({
        webPreferences: {
            preload: path.join(__dirname, "preload.js"),
        },
    })
    // add new window to list of active windows
    windows.push(win)
    // automatically remove window from list when closed
    win.on("closed", () => {
        const winId = windows.indexOf(win)
        winId > -1 && windows.splice(winId,1)
    })
    fileToLoad && win.loadFile(fileToLoad)
    return win
}

// broadcast to all windows opened with createWindow
const broadcast = (eventType, ...params) => {
    windows.forEach(win => win.webContents.send("app:broadcastEvent", {eventType, eventData: [...params]}))
}

// later in your code 
broadcast('customEvent', "parameter1", "parameter2")

in your preload.js you should expose a method to regiseter a listener for broadcasted events

const { contextBridge, ipcRenderer } = require("electron")

contextBridge.exposeInMainWorld('electronAPI', {
    onBroadCastedEvent: (callback) => {
        ipcRenderer.on("app:broadcastEvent", (evt, {eventType, eventData}) => callback(eventType, ...eventData))
    }
})

then in you renderer.js you can register a listener like this:

window.electronAPI.onBroadCastedEvent((eventType, ...eventParams) => {
    console.log(`received broadcast event ${eventType} with data: `, eventParams)
})

Upvotes: 0

Joshua
Joshua

Reputation: 5322

You could make an array of windows, then iterate over them and send a message to each one:

var windowsArr = [];

windowsArr.push(new BrowserWindow({title: "Win 1"}));
windowsArr.push(new BrowserWindow({title: "Win 2"}));

function broadcast (message) {
    for (var i = 0; i < windowsArr.length; i++) {
        windowsArr[i].webContents.send('asynchronous-message', message);
    }
}

Upvotes: 2

martpie
martpie

Reputation: 6080

You are looking for the webContents API. From the same page of documentation in your post:

It is also possible to send messages from the main process to the renderer process, see webContents.send for more information.

Here is the doc for webContents

Upvotes: 3

Related Questions