首页 文章

何时使用远程vs ipcRenderer,ipcMain

提问于
浏览
37

我试图理解电子主要和渲染过程之间的通信 . 文档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示例与我的应用程序一起使用,这看起来很简单 . 在什么情况下应该使用远程模块?

1 回答

  • 62

    来自remote文档:

    在Electron中,与GUI相关的模块(如对话框,菜单等)仅在主进程中可用,而不在渲染器进程中可用 . 为了在渲染器进程中使用它们,必须使用ipc模块将进程间消息发送到主进程 . 使用远程模块,您可以调用主进程对象的方法,而无需显式发送进程间消息,类似于Java的RMI . 从渲染器进程创建浏览器窗口的示例: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模块(虽然它在幕后发生) . 不是说两者是相互排斥的 .

    使用遥控器时的另一个问题 . 是否可以访问主进程中存在的函数而不是模块?

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

    编辑:您可以像平常一样要求它 . 边缘情况是,如果渲染器窗口的当前URL未指向本地文件(未使用file://加载) . 如果您正在加载远程URL,则您的需求路径必须是绝对路径,或者您可以使用远程URL,如下所述 .

    旧:

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

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

    请注意,使用类似遥控器会导致您的代码在主进程的上下文中运行 . 这可能有它的用途,但我会小心 .

    正常情况下需要内置节点模块或 electron

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

    我可以从渲染器访问全局变量吗?

    是 .

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

相关问题