NodeJS contextBridge receiving results from index.js

Viewed 13

I've been able to use the preload.js for sending message to API to get things done. I'm able to get responses just fine from iPC, but I'm not able to relay the responses from iPC back to the renderer and I don't understand what I'm missing.

index.js (main)


// Modules to control application life and create native browser window
const { app, BrowserWindow, remote, ipcMain } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile('index.html');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready',() => {
  createWindow();
  require('./request.js')(mainWindow);
  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

request.js - this is used in index/main thread above to process API requests, in this case requests to winax which I use with a separate 32 bit nodeJs interpreter because I couldn't get it to build for use with the same version of Node I can use for electron

const { ipcMain, ipcRenderer } = require('electron');
  const { spawn } = require('child_process');
module.exports = function(mainWindow){  
  let winax;

  ipcMain.on('winax', (event,arguments) => {
    console.log('winax=');
    console.log(arguments);

    if(winax === undefined) {
      console.log('spawning winax');

      winax = spawn(
        'C:\\Program Files\\nvm\\v14.20.0\\node.exe', 
        [ 'winax_microamp/index.js' ], {
          shell: false,
          stdio: ['inherit', 'inherit', 'inherit', 'ipc' ],
          windowsHide: true
        }
      );
      
    }
    console.log('sending winax arguments');

    /* 
      arguments = {
        method: 'functionToRun', 
        owner: 'requestingProcess', 
        params: { required_params ... }
      }
    */
    winax.send(arguments);

    winax.once('message', (message) => {
      console.log('winax response=')
      console.log(message);
      mainWindow.webContents.postMessage('response', message);
    });
    
  });
 
}

preload.js

'use strict';

// preload.js

// All the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
// MAS: This function executes when the DOM is loaded so we should be able to add button interactions here 
const { contextBridge, ipcRenderer } = require('electron');
let testAccDb = 'C:\\Users\\PZYVC7\\OneDrive - Ally Financial\\Access\\electron_microamp.accdb';

//const spawn = require('child_process').spawn

contextBridge.exposeInMainWorld(
  'request', {

    send: (func) => {
      console.log('request.send.func=');
      console.log(func);

      if(func == 'openStagingTest'){
        let args = {
          method: 'requestStagingDatabase', 
          owner: 'ui',
          params: { 
            path: testAccDb 
          }
        };

        ipcRenderer.send('winax',args);
      } else if(func == 'closeStagingTest') {

          let args = {
            method: 'closeStagingDatabase',
            owner: 'ui'            
          };
    
          ipcRenderer.send('winax',args);
      }
    }, 
    response: (message) => {
      ipcRenderer.on('message', (message) => {      
        console.log('winax reply=');
        console.log(message);
      });
    }
  }
);

window.addEventListener('DOMContentLoaded', () => {

  /*const replaceText = (selector, text) => {
    const element = document.getElementById(selector);
    if (element) element.innerText = text;
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency]);
  }*/
  
});

render.js

'use strict';

onLoad();

function onLoad(){
  /*document.querySelector('.one').addEventListener('click',() => {
    writeLog()
  });*/

  /*var testButton = document.querySelector('button[class=test]');
  testButton.addEventListener('click', (e) => { 
    //C:\\Program Files\\nvm\\v14.20.0\\node.exe
    window.main.asyncProc( '"C:\\Program Files\\nvm\\v14.20.0\\node.exe" winax_microamp/index.js' );
  });*/

  var buttons = document.querySelectorAll('button');
  buttons.forEach((button) => {
    //console.log('button=');
    //console.log(button.className);
    button.addEventListener('click', (event) => {
      window.request.send(button.className);
    });
  });

}
1 Answers

Ugh... ok, so a few things I figured out eventually, I took hours to figure this out, and I'm not 100% sure if I'm understanding it properly so I appreciate any correction.

I think one issue that threw me off for longer than it should have is that the console.log for the preload.js goes into the developer tools rather than the system console like the main thread areas do.

Another thing throwing me off was that I was writing the implementation inside of preload.js, rather than in render.js. I confirmed it does work in both places.

If I want it in preload.js, I leave the implementation like this, and I confirmed it was firing here based on changing the log message a little preload.js

response: (message) => {
      ipcRenderer.on('response', (message) => {      
        console.log('expose reply=');
        console.log(message);
      });
    }
  }

If I want it in render instead, I need my preload to be more basic

response: (message) => {
      ipcRenderer.on('response', message);      
    }

And then I need render to have this to process it there instead.

  window.request.response((event,message) => {
    console.log('winax reply=');
    console.log(message);
  });
Related