IPC Communication not working between Electron and window

纵然是瞬间 提交于 2019-12-12 13:02:30

问题


I am trying to write my first Electron app based on Electron Boilerplate. I am trying to send a simple message from the main Electron process into my window but it seems that the message is not getting send.

The main code I've impmeneted is as follows

background.js ( main Electron process)

// 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 ( Window mapped to mainWindow )

import { ipcRenderer } from "electron";

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

Any idea why the event is not getting received ? I see the console log that the DEV code is running but nothing on the app window side ( In the Developer console log ) The full code can be found at Git Repo

Any help would be appreciated.

Thanks Oliver


回答1:


As document indicates (https://github.com/electron/electron/blob/master/docs/api/web-contents.md#contentssendchannel-arg1-arg2-), It is important to send message once renderer is ready to listen.

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');
    })
  }


来源:https://stackoverflow.com/questions/48384476/ipc-communication-not-working-between-electron-and-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!