electron 在电子设备中广播来自ipcMain的消息

jvidinwx  于 2023-01-15  发布在  Electron
关注(0)|答案(3)|浏览(187)

我需要从electron的主进程向所有渲染器进程广播一条消息。ipcMain没有发送选项,只有一个通过event.sender.send()回复发送者的选项。

yizd12fk

yizd12fk1#

您正在寻找webContents API,请参阅您帖子中的同一页文档:
也可以将消息从主进程发送到呈现器进程,有关详细信息,请参阅webContents.send。
这是webContents的文档

f1tvaqid

f1tvaqid2#

你可以创建一个窗口数组,然后遍历它们并向每个窗口发送一条消息:

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);
    }
}
q5iwbnjs

q5iwbnjs3#

详细阐述“约书亚的回答”
在你的main.js中你可以添加这样的内容

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")

在preload.js中,您应该公开一个方法来注册广播事件的侦听器

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

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

那么在renderer.js中,你可以像这样注册一个监听器:

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

相关问题