问题
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