【问题标题】:Communication between remote Angular app and Electron desktop app远程 Angular 应用程序和 Electron 桌面应用程序之间的通信
【发布时间】:2019-11-03 23:40:37
【问题描述】:

场景如下:

  • 部署在外部服务器中的 Angular 应用
  • 在本地运行的桌面电子应用程序提供远程 url(提供 Angular 的地方)

有没有办法使用电子 API 从 Angular 应用程序与操作系统进行交互?我确实相信 IPC 不会工作,因为它们不在同一个实例上运行,但我想知道是否有人可以提出其他解决方案。

谢谢,贾维

【问题讨论】:

    标签: angular electron ipc communication


    【解决方案1】:

    在做一些研究之后,使用 IPC 来回 Angular 应用似乎是可行的。

    由于 Angular 应用程序在 Renderer Process 中呈现,因此可以调用 ipcRenderer 模块以进行此类通信:

    在 Electron 应用中的 Main Process 中:

    const { ipcMain } = require('electron');
    
    ipcMain.on('customChannel', (event, args) => {
      console.log('event: ', event);
      console.log('args: ', args);
    });
    

    在 Angular 应用上,在组件上:

    // Component implementing OnInit
    
    ngOnInit(): void {
     if ((<any>window).require) {
       try {
        const ipc = (<any>window).require('electron').ipcRenderer;
        ipc.send('customChannel', 'this is a test');
       } catch (error) {
        throw error;
       }
      } else {
         console.warn('Could not load electron ipc');
      }
    }
    

    【讨论】:

      【解决方案2】:

      在上面的示例中,远程 Web 应用程序安装了电子。如果有人想要在没有电子依赖的情况下进行通信,那么我们可以使用 contextBridge。

      在您的电子应用中

      const { contextBridge, ipcRenderer } = require('electron')
      
      contextBridge.exposeInMainWorld(
        'electron',   //This will be exposed as window.electron in your remote app
        {
          doThing: () => ipcRenderer.send('do-a-thing')
        }
      )
      

      在您的远程应用中

      window.electron.doThing()
      

      来源https://www.electronjs.org/docs/api/context-bridge

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-05
        相关资源
        最近更新 更多