electron-egg electron-egg
首页
  • v4.x
  • v3.x
  • v2.x
插件
  • v4.x
  • v3.x
demo
支持
知识点
案例
交流
  • GitHub (opens new window)
  • Gitee (opens new window)
首页
  • v4.x
  • v3.x
  • v2.x
插件
  • v4.x
  • v3.x
demo
支持
知识点
案例
交流
  • GitHub (opens new window)
  • Gitee (opens new window)
❤️成为赞助商
  • 框架

    • 通信
      • http服务
      • socket服务
      • json数据库
      • sqlite数据库
      • 任务
      • 自动更新
      • 软件调用
      • Java服务
    • 操作系统

    • 特效

    • 硬件

    • 优惠券
    • 异常处理
    目录

    通信

    前端(渲染进程)与 主进程 通信 - ipc

    # 发送异步消息

    (推荐)异步回调

      // frontend/src/views/framework/socket/Ipc.vue
      <script>
        import { ipcApiRoute } from '@/api/main'
        handleInvoke () {
          this.$ipc.invoke(ipcApiRoute.ipcInvokeMsg, '异步-回调').then(r => {
            console.log('r:', r);
          });
        },
        async handleInvoke2 () {
          const msg = await this.$ipc.invoke(ipcApiRoute.ipcInvokeMsg, '异步');
          console.log('msg:', msg);
        },
      </script> 
      
      // electron/controller/framework.js
      /**
       * 异步消息类型
       */
      async ipcInvokeMsg(args, event) {
        let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
        const data = args + ' - ' + timeNow;
        return data;
      }
      
      // Make sure to add code blocks to your code group

      # 同步消息

      (不推荐)阻塞执行。任何错误都可能引起界面卡死。

        // frontend/src/views/framework/socket/Ipc.vue
        <script>
          handleSendSync () {
            const msg = this.$ipc.sendSync(ipcApiRoute.ipcSendSyncMsg, '同步');
            this.message3 = msg;
          },
        </script> 
        
        // electron/controller/framework.js
        /**
          * 同步消息类型
          */ 
        async ipcSendSyncMsg(args) {
          let timeNow = dayjs().format('YYYY-MM-DD HH:mm:ss');
          const data = args + ' - ' + timeNow;
          return data;
        }
        
        // Make sure to add code blocks to your code group

        # 长消息

        服务端持续向前端页面发消息

          // frontend/src/views/framework/socket/Ipc.vue
          <script>
            init () {
              // 避免重复监听,或者将 on 功能写到一个统一的地方,只加载一次
              this.$ipc.removeAllListeners(ipcApiRoute.ipcSendMsg);
              this.$ipc.on(ipcApiRoute.ipcSendMsg, (event, result) => {
                console.log('[ipcRenderer] [socketMsgStart] result:', result);
              })
            },
            sendMsgStart() {
              const params = {
                type: 'start',
                content: '开始'
              }
              this.$ipc.send(ipcApiRoute.ipcSendMsg, params)
            },
            sendMsgStop() {
              const params = {
                type: 'end',
                content: ''
              }
              this.$ipc.send(ipcApiRoute.ipcSendMsg, params)
            },
          </script> 
          
          // electron/controller/framework.js
          /**
           * 双向异步通信
           */
          async ipcSendMsg(args, event) {
            const { type, content } = args;
            const data = await this.service.framework.bothWayMessage(type, content, event);
            return data;
          }
          
          // Make sure to add code blocks to your code group

          # 多窗口通信

          子窗口与主进程通信,子窗口互相通信

            // frontend/src/views/framework/socket/Ipc.vue
            <script>
              createWindow(index) {
                this.$ipc.invoke(ipcApiRoute.createWindow, this.views[index]).then(id => {
                  console.log('[createWindow] id:', id);
                })
              },
              async sendTosubWindow() {
                // 新窗口id
                this.newWcId = await this.$ipc.invoke(ipcApiRoute.getWCid, this.windowName);
                this.$ipc.sendTo(this.newWcId, specialIpcRoute.window1ToWindow2, '窗口1通过 sendTo 给窗口2发送消息');
              },
            </script> 
            
            // electron/controller/os.js
            /**
             * 打开新窗口
             */
            createWindow (args) {
              const { type, content, windowName, windowTitle } = args;
              let contentUrl = null;
              if (type == 'html') {
                contentUrl = path.join('file://', electronApp.getAppPath(), content)
              } else if (type == 'web') {
                contentUrl = content;
              } else if (type == 'vue') {
                let addr = 'http://localhost:8080'
                if (Ps.isProd()) {
                  const mainServer = Conf.getValue('mainServer');
                  addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
                }
                contentUrl = addr + content;
              } else {
                // some
              }
              console.log('contentUrl: ', contentUrl);
              const addonWindow = this.app.addon.window;
              let opt = {
                title: windowTitle
              }
              const win = addonWindow.create(windowName, opt);
              const winContentsId = win.webContents.id;
              // load page
              win.loadURL(contentUrl);
              return winContentsId;
            }
            /**
             * 获取窗口contents id
             */
            getWCid (args) {
              const addonWindow = this.app.addon.window;
              // 主窗口的name默认是main,其它窗口name开发者自己定义
              const name = args;
              const id = addonWindow.getWCid(name);
              return id;
            }
            
            // Make sure to add code blocks to your code group

            # 完整代码

            • github前端代码 (opens new window) -
            • github主进程代码 (opens new window)
            • gitee前端代码 (opens new window)
            • gitee主进程代码 (opens new window)
            上次更新: 2025/06/06, 07:21:49
            http服务

            http服务→

            Theme by Vdoing | Copyright © 2023-2025 哆啦好梦 | 京ICP备15041380号-2
            • 跟随系统
            • 浅色模式
            • 深色模式
            • 阅读模式
            ×