何时使用远程与 ipcRenderer、ipcMain

When to use remote vs ipcRenderer, ipcMain

我正在尝试了解电子主进程和渲染进程之间的通信。文档 https://github.com/electron/electron/blob/master/docs/api/remote.md 指出 "remote module provides a simple way to do inter-process communication (IPC) between the renderer process and the main process."

但是,关于如何设置它的文档非常少。

我可以让 IPC 示例与我的应用程序一起工作,这看起来很简单。 remote模块应该在什么场景下使用?

来自 remote 文档:

In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process.With the remote module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java's RMI. An example of creating a browser window from a renderer process:

const remote = require('electron').remote;
const BrowserWindow = remote.BrowserWindow;

var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://github.com');

基本上,remote 模块可以很容易地完成通常仅限于渲染进程中主进程的工作,而无需来回发送大量手动 ipc 消息。

因此,在渲染器进程中,而不是:

const ipc = require('electron').ipcRenderer;
ipc.send('show-dialog', { msg: 'my message' });
ipc.on('dialog-shown', () => { /*do stuff*/ });

(然后在主体中编写代码来响应这些消息)。

您可以在渲染器中完成所有操作:

const remote = require('electron').remote;
const dialog = remote.require('dialog')

dialog.showErrorBox('My message', 'hi.');

ipc 模块不是明确需要的(尽管它在幕后发生)。并不是说两者是相互排斥的。

One further question when using remote. Is it possible to access a function that exists in the main process rather than a module ?

我认为您真正要问的是:如何在 main/renderer 进程之间共享代码以及如何在渲染器中需要一个模块?

编辑:您可以像往常一样要求它。如果您的渲染器 window 的当前 URL 未指向本地文件(未使用 file:// 加载),则这是一种边缘情况。如果您正在加载远程 URL,您的要求路径必须是绝对路径,或者您可以像我下面所说的那样使用远程。

旧:

这是 remote 的另一个用例。例如:

remote.require('./services/PowerMonitor.js')

请注意,像这样使用远程会导致您的代码在主进程的上下文中成为 运行。这可能有它的用途,但我会小心。

内置节点模块或electron像平常一样需要:

require('electron')
require('fs')

Can I access global variables from the renderer?

是的。

//in main
global.test = 123;
//in renderer
remote.getGlobal('test') //=> 123