Electron实战(二):将Node.js和UI能力(app/BrowserWindow/dialog)等注入html

文章目录

上一篇:Electron实战(一):环境搭建/Hello World/打包exe

设置webPreferences参数

为了能够在html/js中访问Node.js提供fs等模块,需要在new BrowserWindow(config)的时候,设置一些参数:

js 复制代码
//LuckyTools/index.js
const mainWindow = new BrowserWindow({
    icon: iconPath,
    width: 800,
    height: 600,
    webPreferences: {
        // 赋予此窗口页面中的JavaScript访问Node.js环境的能力
        nodeIntegration: true,
        //Election 14之前,需要打开remote模块,方便main进程调用UI渲染进程的dialog/menu等
        enableRemoteModule: true, 
        // 官网似乎说是默认false,但是这里必须设置contextIsolation
        contextIsolation: false,
    }
});

Election 14之前,只需要在webPreferences设置中打开remote模块,即可在main进程调用UI渲染进程的dialog/menu等。

安装@electron/remote

Electron 14开始remote模块已被移除,为了能够在html中访问Electron的UI能力(app/BrowserWindow/dialog),需要额外单独安装electron/remote包。

bash 复制代码
npm install @electron/remote --save

安装后,在html中引用UI模块的方式也有变化,官方给的代码是:

js 复制代码
// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote

// Replace with:
const { BrowserWindow } = require('@electron/remote')

main进程中初始化

js 复制代码
// In the main process:
require('@electron/remote/main').initialize();
// 必须启用,html中才能访问
require("@electron/remote/main").enable(mainWindow.webContents);

最终,完整的index.js文件内容如下:

js 复制代码
//app 模块,控制整个应用程序的事件生命周期。
//BrowserWindow 模块,它创建和管理程序的窗口。
const { app, BrowserWindow } = require('electron')
const path = require('path')
const iconPath = path.join(__dirname, './src/res/icon.ico')

//在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口
app.on('ready', () => {
    require('@electron/remote/main').initialize();
    //创建一个窗口
    const mainWindow = new BrowserWindow({
        icon: iconPath,
        // width: 800,
        // height: 600,
        webPreferences: {
            // 赋予此窗口页面中的JavaScript访问Node.js环境的能力
            nodeIntegration: true,
            // 打开remote模块,方便main进程调用UI渲染进程的dialog/menu等
            enableRemoteModule: true,   
            // 官网似乎说是默认false,但是这里必须设置contextIsolation
            contextIsolation: false,
          }
    });
    // 必须启用,html中才能访问
    require("@electron/remote/main").enable(mainWindow.webContents);
    // mainWindow.setMenu(null);
    //窗口加载html文件
    mainWindow.loadFile('./src/index.html')
})

html中使用dialog

js 复制代码
//test.html
var fs = require("fs");
var elec = require('electron');
console.log(elec);
var EUI = require('@electron/remote');
console.log(EUI);
var dialog = EUI.dialog;//可以直接使用dialog模块了

var filePath = dialog.showOpenDialogSync({
    title: '选择文件',
    properties: ['openFile']
});
if (!filePath) {
    console.log("cancel: ", filePath);
}
fs.readFile(filePath[0], { encoding: 'utf-8' }, (err, data) => {
    if (err) throw err;
    console.log(data);
});

打印出EUI发现,所有UI相关的模块都被注入进来了:

踩坑

不知道是不是网络原因,笔者安装@electron/remote报错:

text 复制代码
npm install @electron/remote --save
npm WARN old lockfile
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/electron-packger - Not found
npm ERR! 404
npm ERR! 404  'electron-packger@^24.9.1' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in: D:\env\nodejs\node_cache\_logs\2024-02-04T03_52_08_843Z-debug-0.log

接着尝试安装cnpm:npm install -g cnpm --registry=https://registry.npm.taobao.org

结果依然报错:

bash 复制代码
PS D:\dev\web\work\LuckyTools> npm install -g cnpm --registry=https://registry.npm.taobao.org
npm ERR! code CERT_HAS_EXPIRED
npm ERR! errno CERT_HAS_EXPIRED
npm ERR! request to https://registry.npm.taobao.org/cnpm failed, reason: certificate has expired

npm ERR! A complete log of this run can be found in: D:\env\nodejs\node_cache\_logs\2024-02-04T06_08_20_084Z-debug-0.log

解决方式:

bash 复制代码
#清除npm缓存
npm cache clean --force
#取消ssl验证
npm config set strict-ssl false
#之后再npm install 你想安装的东西

查看cnpm版本:

bash 复制代码
 cnpm --version
cnpm@9.4.0 (D:\env\nodejs\node_global\node_modules\cnpm\lib\parse_argv.js)
npm@9.9.2 (D:\env\nodejs\node_global\node_modules\cnpm\node_modules\npm\index.js)
node@20.10.0 (D:\env\nodejs\node.exe)
npminstall@7.12.0 (D:\env\nodejs\node_global\node_modules\cnpm\node_modules\npminstall\lib\index.js)
prefix=D:\env\nodejs\node_global
win32 x64 10.0.22621
registry=https://registry.npmmirror.com

再安装:

bash 复制代码
cnpm install @electron/remote --save
# 略去一些输出,终于安装成功了
dependencies:
+ @electron/remote ^2.1.2

参考文档

Electron 14开始remote模块已被移除,可用@electron/remote包代替:https://www.electronjs.org/docs/latest/breaking-changes#removed-remote-module

相关推荐
凉介Nova2 天前
Electron 应用体积从 190MB+ 到 90MB:一次「release 目录反推」的瘦身实战(electron-builder + Vite)
electron
winfredzhang2 天前
零基础打造轻量级桌面备忘录:Electron 核心技术实战
前端·javascript·electron·备忘录
放逐者-保持本心,方可放逐2 天前
electron 中的那些事(很关键)-核心要点补充
前端·javascript·electron
每日出拳老爷子2 天前
【客户端方案】Electron / 原生客户端在内网会议中的取舍与坑点
服务器·electron·远程工作·流媒体·视音频
南山老沙2 天前
VUE 项目通过electron-builder打包成桌面应用
electron·vue
贺今宵4 天前
electron-vue无网络环境,读取本地图片/文件展示在页面vue中protocol
前端·javascript·electron
xiaoyan20154 天前
2026原创Electron39.2+Vue3+DeepSeek从0-1手搓AI模板桌面应用Exe
vue.js·electron·deepseek
「、皓子~4 天前
AI 创作系列(34)海狸IM桌面版 v1.1 正式发布:Vite + Electron 性能优化与体验升级
前端·人工智能·electron·开源·开源软件·im
光影少年4 天前
electron通信方式有哪些?
前端·javascript·electron
学海无涯,行者无疆5 天前
把 Web App 装进客户端——Tauri框架实战:托盘功能、消息通知、构建安装程序
electron·tauri·单例运行·web应用客户端化·托盘通知·tauri实战·tauri框架