I've read through Electron's context isolation, IPC, and security docs, along with this post about using nodeIntegration, and this post about preload.js. It looks like there are a lot of different ways to accomplish similar tasks and I'm not sure which is the best (safe, easy, etc.).
I know you can simply enable nodeIntegration
in renderer processes to access Node outside of the main process. Every source recommended against that for the most part.
Here's where I'm confused. An example from Electron's documentation says you can do something like what's below.
preload.js
// preload with contextIsolation disabled
window.myAPI = {
doAThing: () => {}
}
renderer.js
// use the exposed API in the renderer
window.myAPI.doAThing()
preload.js has access to Node APIs so technically I could load in all Node processes and then access them in my renderers.
However, I also read about IPC.
part of main.js
ipcMain.on('set-title', (event, title) => {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
})
preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})
renderer.js
const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
const title = titleInput.value
window.electronAPI.setTitle(title)
});
For example, let's say I wanted to implement a function using an external npm module. Would I incorporate it in preload.js and call it from my renderer, or incorporate it in main.js, use ipcRenderer in preload.js with a channel for the function, and then call it from my renderer?