Different ways to communicate between main and renderer process

No BS. Code says it all.

Main process

'use strict'

var electron = require('electron');  
var {app, BrowserWindow, ipcMain} = electron;  
var mainWindow = null;

app.on('ready', () => {  
    mainWindow = new BrowserWindow({
        width: 200,
        height: 200
    });
    mainWindow.loadURL(`file://${__dirname}/index.html`);
});

// Listen for async message from renderer process
ipcMain.on('async', (event, arg) => {  
    // Print 1
    console.log(arg);
    // Reply on async message from renderer process
    event.sender.send('async-reply', 2);
});

// Listen for sync message from renderer process
ipcMain.on('sync', (event, arg) => {  
    // Print 3
    console.log(arg);
    // Send value synchronously back to renderer process
    event.returnValue = 4;
    // Send async message to renderer process
    mainWindow.webContents.send('ping', 5);
});

// Make method externaly visible
exports.pong = arg => {  
    //Print 6
    console.log(arg);
}

Renderer process

var {ipcRenderer, remote} = require('electron');  
var main = remote.require("./main.js");

// Send async message to main process
ipcRenderer.send('async', 1);

// Listen for async-reply message from main process
ipcRenderer.on('async-reply', (event, arg) => {  
    // Print 2
    console.log(arg);
    // Send sync message to main process
    let mainValue = ipcRenderer.sendSync('sync', 3);
    // Print 4
    console.log(mainValue);
});

// Listen for main message
ipcRenderer.on('ping', (event, arg) => {  
    // Print 5
    console.log(arg);
    // Invoke method directly on main process
    main.pong(6);
});

Cheers!

About Vjekoslav Ratkajec

Software developer from Zagreb, Croatia. Love programming, running, hiking and biking. Adore nature and animals. Also author of this blog.

Comments