I am struggling with incorporating ipcRenderer
into the 'frontend' code of my electron app. Although I found examples in the documentation that use require
, this method is not accessible on the frontend side where I am utilizing Angular.
In the electron docs - https://www.electronjs.org/docs/tutorial/process-model#preload-scripts - there is an example demonstrating how to connect variables from the main process to the renderer process window. However, when attempting to utilize these attached variables, they return as undefined
.
main.js
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "#ffffff",
preload: './preload.js'
});
win.loadFile('dist/foobar/index.html') // I get index.html after building angular code
win.on("closed", () => {
win = null;
});
}
app.on("ready", createWindow);
preload.js
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("ipcRenderer", {ipcRenderer}); //exposing ipcRenderer to the window in renderer process
electron service (angular code)
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ElectronService {
constructor() { }
getIpcRenderer(){
return (<any>window).ipcRenderer;
}
}
angular component
export class FoobarComponent {
constructor(private es: ElectronService) {}
test(){
console.log(this.es.getIpcRenderer()); // this logs as undefined
}
}
The Issue at Hand
In the provided code snippet, the test()
function outputs undefined. Why does window.ipcRenderer remain undefined? Even after running console.log(window)
, IPC renderer cannot be located within the list of properties.
Is there a more effective manner to expose ipcRenderer to my Angular code? As mentioned in the linked document,
This feature is incredibly useful for two main purposes:
- By exposing ipcRenderer helpers to the renderer, you can use inter-process communication (IPC)
to trigger main process tasks from the renderer (and vice-versa).- [...]
I believe that contextBridge.exposeInMainWorld
is the optimal approach based on the documentation, but please advise if this is outdated or if there exists a better alternative.
My Electron App Execution Process
- I compile Angular code using
ng build --prod
- I launch the electron app by executing
electron .
(main.js serves as the entry point)