gpt4 book ai didi

javascript - 何时使用远程与 ipcRenderer、ipcMain

转载 作者:IT王子 更新时间:2023-10-29 03:04:30 26 4
gpt4 key购买 nike

我正在尝试了解 Electron 主进程和渲染器进程之间的通信。文档 https://github.com/electron/electron/blob/master/docs/api/remote.md指出“远程模块提供了一种在渲染器进程和主进程之间进行进程间通信(IPC)的简单方法。”

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

我可以让 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 ?

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

编辑:您可以像往常一样要求它。如果您的渲染器窗口的当前 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

关于javascript - 何时使用远程与 ipcRenderer、ipcMain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36548228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com