Electron - 我的应用程序可以与主进程和渲染器进程通信吗? [英] Electron - Can my app communicate with the main and renderer processes?

查看:11
本文介绍了Electron - 我的应用程序可以与主进程和渲染器进程通信吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个非常非常基本的电子应用程序——标准的 hello world 类型,你基本上有一个 HTML 文件,上面写着Hello, World"——它位于电子的app"目录中,然后是运行应用程序时通过 main.js 加载.

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:

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

这篇关于Electron - 我的应用程序可以与主进程和渲染器进程通信吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆