电子-我的应用程序可以与主进程和渲染器进程进行通信吗? [英] Electron - Can my app communicate with the main and renderer processes?
问题描述
我已经写了一个非常非常基础的电子应用程序-标准的hello world类型,您在那里基本上有一个HTML文件,上面写着 Hello,World,该文件位于电子文件中的 app目录中,然后
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.
现在,假设我希望能够与这些进程(主要是渲染器)进行通信两者!)都可以从我的应用程序中的javascript中完成吗?我在网上找不到任何东西-但我的主要问题可能是我一开始甚至都不知道要搜索什么。我对Electron很陌生。
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.
推荐答案
我想您正在谈论主要过程和其他浏览器窗口。
I suppose you are talking about the main process and other browser windows.
您可以使用 BrowserWindow.webContents.send(channel [,arg1] [,arg2] [,...])
来将消息从主进程发送到浏览器窗口,然后使用 ipcRenderer
接收消息。举个例子:
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:
主流程:
subWindow.webContents.send("foo","bar");
名为 BrowserWindow
> subWindow :
The BrowserWindow
called subWindow
:
var ipc=require("electron").ipcRenderer;
ipc.on("foo",(event, arg1) => {
console.log(arg1); //Outputs "bar"
});
要将数据从浏览器窗口发送到主进程时,请使用 remote.app.emit
。使用 app.on
接收它。相同的示例:
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:
主过程:
var app=require("electron").app;
app.on("test",(arg) => {
if (arg=="hey!") console.log("ha!");
}
子窗口:
require("electron").remote.app.emit("test","hey!");
这篇关于电子-我的应用程序可以与主进程和渲染器进程进行通信吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!