首页 > 解决方案 > 访问 Electron 5 中的节点模块

问题描述

由于 Electron 的最新版本 5 出于安全原因,nodeIntegration 默认为 false,那么推荐的访问节点模块的方式是什么?有没有办法在没有nodeIntegration的情况下与主进程通信?

标签: electron

解决方案


使用预加载脚本,您可以通过仅将 ipcRenderer 对象导入窗口来与主进程通信。

为此,您必须在 browserWindow webPreferences 中指定预加载脚本的绝对路径。


  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload : path.join(__dirname , '/preload_script.js')
    }
  })

并在 preload_script.js 中注入 ipcRenderer 对象

window.ipcRenderer = require('electron').ipcRenderer;

您可以使用 html 脚本中的 window.ipcRenderer 对象与主进程/或另一个渲染器进程进行通信。


推荐阅读