mainWindow.webContents.send() not received by ipcRenderer.on() function

Viewed 10919

In the electron main.js I am wanting to send an event from a child Window to a mainWindow. The way I thought to do this was by sending an event from childWindow to the Main Process, and the Main Process then sends an event to the mainWindow.

ipcMain.on('submit-form-data', (event, data) => {

    if (data) {
        console.log('send data to main window')
        mainWindow.webContents.send('submitted-form', data)
    }

        childWindow.hide();
    })

The childWindow successfully send it's form data to the main process. But when I want the main process to then send that data to the mainWindow, the event is not being picked up. I don't have an idea of what I can try to get this to work.

index.html in the mainWindow

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Main Window</title>
  <script>
      var ipcRenderer = nodeRequire("electron").ipcRenderer;

      ipcRenderer.on("submitted-form", function (event, data) {
        alert('received data'); // this never gets called :(
      });
</script>
2 Answers

Wrap your mainWindow.webContents.send('submitted-form', data); line with mainWindow.webContents.on('did-finish-load', ()=>{});. It solved my problem, hope helps you too.

mainWindow.webContents.on('did-finish-load', ()=>{
  mainWindow.webContents.send('submitted-form', data);
})

It works, you'll need to enable nodeIntegration on the BrowserWindow and fix the import of ipcRenderer:

app.js (Main process)

const {app,BrowserWindow} = require("electron")
const url = require("url")
const path = require("path")

let mainWindow

app.on("ready", function() {
    mainWindow = new BrowserWindow({
        width: 500,
        height: 300,
        webPreferences: {
            nodeIntegration: true
        }
    })
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, "index.html"),
        protocol: "file:",
        slashes: true
    }))

    mainWindow.toggleDevTools()

    setTimeout(() => {
        console.log("sending message from main process")
        mainWindow.webContents.send("submitted-form", "hello")
    }, 3000)
})

index.html (Renderer process)

<!DOCTYPE html>
<html>
<body>
Index with renderer javascript
</body>
<script type="text/javascript">
    const { ipcRenderer } = require("electron")

    ipcRenderer.on("submitted-form", function (event, data) {
        console.log("received data", data)

        alert("received data")
    });
</script>
</html>
Related