Electron 中的 nodeIntegration vs preload.js vs IPC答案
nodeIntegration vs preload.js vs IPC in ElectronElectron 中的 nodeIntegration vs preload.js vs IPC
我已经阅读了 Electron 的 context isolation、IPC 和 security 文档,以及 this post about using nodeIntegration 和 this post about preload.js。看起来有很多不同的方法可以完成类似的任务,我不确定哪种方法***(安全、简单等)。
我知道您可以简单地在渲染器进程中启用nodeIntegration
以访问主进程之外的 Node。大多数情况下,每个来源都建议反对。
这就是我感到困惑的地方。 Electron 文档中的一个示例表明您可以执行以下操作。
preload.js
// preload with contextIsolation disabled
window.myAPI = {
doAThing: () => {}
}
renderer.js
// use the exposed API in the renderer
window.myAPI.doAThing()
preload.js 可以访问 Node API,因此从技术上讲,我可以加载所有 Node 进程,然后在我的渲染器中访问它们。
不过,我也读过 IPC。
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)
});
例如,假设我想使用外部 npm 模块实现一个功能。我是将它合并到 preload.js 中并从我的渲染器中调用它,还是将它合并到 main.js 中,在 preload.js 中使用带有函数通道的 ipcRenderer,然后从我的渲染器中调用它?