I need to spawn a child process in electron (currently MPV instance). As the contextIsolation, I am unable to directly use node in renderer, but If I understand correctly, in preload script it should be avaiable, but writing:
import child_process from 'child_process'
in preload.ts throws error in console:
VM39 sandbox_bundle:2 Error: module not found: child_process
at preloadRequire (VM39 sandbox_bundle:2:82852)
at <anonymous>:3:23
at runPreloadScript (VM39 sandbox_bundle:2:83516)
at VM39 sandbox_bundle:2:83813
at VM39 sandbox_bundle:2:83968
at ___electron_webpack_init__ (VM39 sandbox_bundle:2:83972)
at VM39 sandbox_bundle:2:84095
So I tried another approach and used IPC. So in renderer.ts I wrote
window.electronAPI.spawn('/usr/bin/mpv', {})
in preload.ts:
import { ipcRenderer, contextBridge } from 'electron'
contextBridge.exposeInMainWorld('electronAPI', {
spawn: (path: string, options: object) => ipcRenderer.invoke('spawnApp', path, options)
})
and in main.ts
ipcMain.handle('spawnApp', (event, path, options) => {
return child_process.spawn(path, options);
})
which works and child process is spawned, but the problem is, that the child process reference can not be returned back to renderer.ts as it throws error in console:
Uncaught (in promise) Error: Error invoking remote method 'spawnApp': Error: An object could not be cloned
what is correct way to handle it?
Electron 30.x, node 20.x
I tried IPC approach and preload.ts approach
Alex Krátký is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.