04. Electron Remote模块的使用方式
当我们知道了 Electron 有主进程和渲染进程后,我们还要知道一件事,就是 Electron 的 API 方法和模块也是分为可以在主进程和渲染进程中使用。那如果我们想在渲染进程中使用主进程中的模块方法时,可以使用Electron Remote
解决在渲染进程和主进程间的通讯。本文我们就实现一个通过 Web 中的按钮打开新窗口。
渲染进程中打开新窗口
这里我为了节省时间直接按照 03 节文章的程序进行改写,在项目根目录下,新建一个index2.html
文件,然后快速生成 html 的基本结构,编写一个按钮,引入渲染的 js 页面。代码如下:
<!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> </head> <body> <button id="btn">打开新的窗口</button> <script src="render/index2.js"></script> </body> </html>
接着修改main.js
文件:
var electron = require('electron'); // 引入 electron 模块 var app = electron.app; // 创建 electron 引用 var BrowserWindow = electron.BrowserWindow; // 控制窗口引用 var mainWindow = null; // 声明要打开的主窗口 app.on('ready', () => { mainWindow = new BrowserWindow({ width:500, height:500, webPreferences: { contextIsolation: false, worldSafeExecuteJavaScript: false, webSecurity: false, nodeIntegration: true, // 是否集成 node.js,解决 require is not defined 问题 nodeIntegrationInWorker: true, webviewTag: true, // 解决 webview 无法显示问题 enableRemoteModule: true } }); // 设置打开的窗口大小 mainWindow.loadFile('index2.html'); // 加载 HTML 页面 // 监听关闭事件,把主窗口设置为 null mainWindow.on('closed', () => { mainWindow = null; }) })
然后在render
文件夹下,新建一个index2.js
文件,然后编写如下代码。
const btn = this.document.querySelector("#btn"); const BrowserWindow = require('electron').remote.BrowserWindow; window.onload = function () { btn.onclick = () => { newWin = new BrowserWindow({ width: 500, height: 500 }); newWin.loadFile("yellow.html") newWin.on('closed', () => { newWin = null; }) } }
这时候还没有yellow.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> </head> <body style="background: yellow;"> <h1>我是黄色页面</h1> </body> </html>
然后我们在终端中运行electron .
,如果一切正常,就可以顺利打开一个新的窗口:
这个窗口可以顺利打开主要的功劳就是electron remote
。它让我们有了很多 pc 端的原生能力,剩下的功能会在后续文章中继续学习。你可以跟着我先把本文的例子效果做出来。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 04. Electron Remote模块的使用方式
码云笔记 » 04. Electron Remote模块的使用方式
高版本 require(electron).remote.BrowserWindow 报错 undefined,是因为从V14开始移除了remote