我已经阅读了 Electron 的 上下文隔离, 进程间通信 和 安全 文档,以及此篇有关使用 nodeIntegration 的文章和此篇有关 preload.js 的文章。看起来有很多不同的方法可以完成类似的任务,我不确定哪种是最好的(安全、易用等)。
我知道你可以在渲染器进程中简单地启用
这就是我困惑的地方。Electron 文档中的一个示例显示可以像下面这样做。
不过,我也了解到了 IPC。
例如,假设我想使用外部npm模块来实现一个函数。我应该将其合并到preload.js中,并从渲染器调用它,还是将其合并到main.js中,在preload.js中使用ipcRenderer创建一个通道以调用该函数,然后再从渲染器中调用它呢?
我知道你可以在渲染器进程中简单地启用
nodeIntegration
来访问主进程之外的 Node。但大多数来源都不建议这样做。这就是我困惑的地方。Electron 文档中的一个示例显示可以像下面这样做。
preload.js
// preload with contextIsolation disabled
window.myAPI = {
doAThing: () => {}
}
renderer.js
// use the exposed API in the renderer
window.myAPI.doAThing()
可以访问 Node APIs,因此从技术上讲,我可以加载所有的 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创建一个通道以调用该函数,然后再从渲染器中调用它呢?