Electron学习笔记 - 渲染进程使用主进程模块(remote)
一、主/渲染进程可使用的模块
在下面这个网址可以查到主进程和渲染进程可使用的模块。
https://www.electronjs.org/docs/latest/api/app
在主进程,可以使用app、autoUpdater、BrowerView、BrowserWindows、clipboard等模块;在渲染进程可以使用clipboard, contextbridge, crashReporter等模块。
接下来我们讲如何在渲染进程使用主进程的模块。
二、渲染进程使用主进程模块(未安装remote模块)
我们先直接在渲染进程使用主进程模块,看程序会出什么报告。
再安装和调用remote模块,达到调用主进程模块的效果。
BrowserWindow。
1. 修改index.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="css/base.css"> <script src="renderer/index.js"></script> </head> <body> <h2>这是渲染进程主窗口</h2> <ul> <li>主窗口里面的内容</li> <li>主窗口里面的内容</li> <li>主窗口里面的内容</li> <li>主窗口里面的内容</li> <li>主窗口里面的内容</li> </ul> <button id="btn">打开</button> </body> </html>
- 增加index.js文件
index.js实现的就是点击按钮打开一个窗口的功能。代码如下:
/* 尝试使用主进程模块 - BrowserWindow */ const { BrowserWindow } = require("electron"); const path = require("path"); window.onload=()=>{ var btnDom = document.querySelector("#btn"); btnDom.onclick=()=>{ //点周按钮,调用主进程模块BrowserWindow const secondWin = new BrowserWindow( { width: 100, height: 600, webPreferences: { nodeIntegration: true, //允许渲染进程使用nodejs contextIsloation: false //允许渲染进程使用nodejs } }); secondWin.loadFile(path.join(__dirname,"second.html")); } }
运行后出现如下报错:

这时,我们来安装remote模块。
三、渲染进程使用主进程模块(正确方法,安装remote模块)
在渲染进程,通过remote模块调用主进程中的。
1. 安装remote模块
npm install --save @electron/remote
2. 在主进程加载remote模块
const { app, BrowserWindow } = require("electron"); const path = require("path"); const remote = require("@electron/remote"); remote.initialize(); const createWindow=()=>{ const mainWindows = new BrowserWindow({ width: 800, height: 400, webPreferences: { nodeIntegration : true, //允许渲染进程使用Nodejs contextIsolation : false //允许渲染进程使用Nodejs } }); mainWindows.loadFile(path.join(__dirname, "index.html")); //打开页面调试 mainWindows.webContents.openDevTools(); //打开调试模式 remote.enable(mainWindows.webContents); } //监听应用的启动事件 app.on("ready", createWindow);
主要是下面三条代码:
const remote = require("@electron/remote");
remote.initialize();
remote.enable(mainWindows.webContents);
3. 在渲染进程修改BrowswerWindow引入方式
在index.js文件,将
const { BrowserWindow } = require("electron");
改为
const { BrowserWindow } = require("@electron/remote");
运行,点击打开按钮,即成功新建了一个窗口。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2020-07-06 zTree jQuery 树插件的使用(实例讲解)