【问题标题】:IPC Communication not working between Electron and window电子和窗口之间的 IPC 通信不起作用
【发布时间】:2018-07-01 06:07:15
【问题描述】:

我正在尝试基于 Electron Boilerplate 编写我的第一个 Electron 应用程序。我正在尝试从主电子进程向我的窗口发送一条简单的消息,但似乎没有发送消息。

我实现的主要代码如下

background.js(主 Electron 进程)

// Window setup
app.on("ready", () => {
  mainWindow = new BrowserWindow({
  width: 1000,
  height: 300,
  frame: false,
  resizable: false,
  transparent: true,    
  });  
  mainWindow.setIgnoreMouseEvents(true);
  mainWindow.hide();

  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, "app.html"),
      protocol: "file:",
      slashes: true
    })
  );

  const ret = globalShortcut.register(getKeyboardShortCut(), () => {
    mainWindow.isVisible ? mainWindow.hide() :  mainWindow.show();
  })

  if(isDev()){
    mainWindow.openDevTools();
    mainWindow.setIgnoreMouseEvents(false);
    console.log("======== DEV ==========");
    mainWindow.show();
    mainWindow.webContents.send('test','This is a test');
  }
});

app.js(窗口映射到 mainWindow)

import { ipcRenderer } from "electron";

ipcRenderer.on('test', (event, text) => { console.log("Received test 
message:", text)});
console.log(ipcRenderer);

知道为什么没有收到活动吗?我看到 DEV 代码正在运行的控制台日志,但在应用程序窗口一侧没有任何内容(在开发人员控制台日志中)完整代码可以在 Git Repo

找到

任何帮助将不胜感激。

谢谢 奥利弗

【问题讨论】:

    标签: electron


    【解决方案1】:

    如文档所示 (https://github.com/electron/electron/blob/master/docs/api/web-contents.md#contentssendchannel-arg1-arg2-),发送消息很重要一旦渲染器准备好收听

    if(isDev()){
        mainWindow.openDevTools();
        mainWindow.setIgnoreMouseEvents(false);
        console.log("======== DEV ==========");
        mainWindow.show();
        // send after did-finish-load
        mainWindow.webContents.on('did-finish-load', () => {
          mainWindow.webContents.send('test','This is a test');
        })
      }
    

    【讨论】:

    • 感谢您的回复。但是代码在 app.on('ready') 中运行,我认为这意味着渲染器已准备好。 (我修复了格式,以便更清楚地表明它确实在该部分中)
    • 不要混淆app 实例就绪和renderer 实例就绪。这两个是不同的。你可以让你的应用实例准备好,但这并不意味着你的渲染器上下文已经准备好了。
    • 抱歉,我没有看到您对代码所做的更改(我一大早就检查了)。我尝试添加您建议的代码,最后它起作用了。非常感谢您的帮助
    猜你喜欢
    • 2021-03-22
    • 2019-02-20
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2011-03-22
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多