Electron - Can my app communicate with the main and renderer processes?

寵の児 提交于 2019-12-07 04:04:18

问题


I have written a very, very basic electron application - The standard hello world type, where you basically have a HTML file which says "Hello, World" - and that lives in the "app" directory within electron, and then is loaded via main.js when you run the app.

Now, lets say I want to be able to maybe communicate with either of those processes (main, or renderer, preferably both!) from the javascript within my application, can that be done? I can't really find anything online about it - but my main problem might be that I don't really even know what to be searching for in the first place. I am very new to Electron.


回答1:


I suppose you are talking about the main process and other browser windows.

You can use BrowserWindow.webContents.send(channel[, arg1][, arg2][, ...]) to send messages from the main process to to a browser window, and receive it using ipcRenderer. Take this example:

Main process:

subWindow.webContents.send("foo","bar");

The BrowserWindow called subWindow:

var ipc=require("electron").ipcRenderer;
ipc.on("foo",(event, arg1) => {
    console.log(arg1); //Outputs "bar"
});

When you want to send data from the browser window to the main process, use remote.app.emit. Receive it using app.on. The same example:

Main process:

var app=require("electron").app;
app.on("test",(arg) => {
    if (arg=="hey!") console.log("ha!");
}

subWindow:

require("electron").remote.app.emit("test","hey!");


来源:https://stackoverflow.com/questions/43859394/electron-can-my-app-communicate-with-the-main-and-renderer-processes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!