4

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

Oliver
  • 89
  • 2
  • 8

1 Answers1

11

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');
    })
  }
OJ Kwon
  • 4,385
  • 1
  • 20
  • 24
  • Thanks for the reply. But the code is running within app.on('ready') which I thought meant the renderer is ready. ( I fixed the formatting to make it clearer that it is indeed in that section ) – Oliver Jan 23 '18 at 00:06
  • don't be confused between `app` instance ready and `renderer` instance is ready. Those two are different. You can make your app instance ready, but that doesn't mean your renderer context is ready. – OJ Kwon Jan 23 '18 at 00:19
  • Sorry I didn't see the change in the code you made ( I checked early in the morning ). I tried to add the code you suggest and finally it worked. Thanks a lot for your help – Oliver Jan 23 '18 at 11:52