Angular 7 + Electron Main Process and Renderer Process Communication
Process Types in Electron
In Electron, there are two types of processes: the main process and the renderer process.
The renderer process can be understood as the view layer — the process that displays pages, which we’re very familiar with.
Here you can use Node.js API capabilities as well as perform browser operations we’re already used to.
But when you need to invoke operations that only the main process can handle, you need a communication mechanism to tell the main process what you want to do.
IPC Communication
Renderer Sends Notification to Main Process
//index.html, renderer process sends notification
const electron = require('electron')
const ipcRenderer = electron.ipcRenderer
ipcRenderer.send('main-process-messages','hellow')
// main.js main process receives notification
const { ipcMain } = require('electron');
ipcMain.on('main-process-messages', function(event, message) {
console.log(message)
});
Main Process Sends Notification to Renderer Process
// main.js
mainWindow.webContents.send('main-process-messages', 'main-process-messages show')
//index.html, renderer process receives message
const electron = require('electron')
const ipcRenderer = electron.ipcRenderer
ipcRenderer.on('main-process-messages', function(event, message){
alert(message)
})
How to Use in an Angular Project
When you directly require('electron') in an Angular project, it will throw an error.
ERROR in ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'fs' in '###/node_modules/electron'
ERROR in ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'path' in '###/node_modules/electron'
So what should we do?
- Create an
electron.service.ts
// Example code
import { Injectable } from '@angular/core';
import {} from 'electron';
import Fs from 'fs';
@Injectable({
providedIn: 'root'
})
export class ElectronService {
constructor() {
// check if platform is electron
const isElectron: boolean = window && window['process'] && window['process'].type;
if (isElectron) {
const fs: typeof Fs = window['require']('fs');
const app: Electron.App = window['require']('electron').remote;
}
}
electron = window['require']('electron');
}
When we need electron, just import this service directly.