安装(建议使用淘宝镜像)
前提:已安装node.js
全局安装
npm install electron -g
局部安装
npm install electron --save-dev
验证安装成功
npx electron -v
Electron的运行流程
![Electron 运行流程]()
Electron模块分类
![img]()
Electron+Vue项目搭建
vue create 项目名称
yarn add -D electron //安装electron
vue add electron-builder //结合vue和electron 会生成background.js主进程文件 package.json文件增加命令
app模块(控制应用程序的生命周期)
app.on:的事件促发条件
ready(应用程序初始化开始)→browser-window-created(窗口创建完成触发)→before-quit(窗口关闭之前)→will-quit(窗口关闭应用未关闭)→quit(应用关闭)
app.whenReady().then 程序初始化过程
app.requestSingleInstanceLock() 返回true或false 禁止应用双开
BrowserWindow模块(控制应用窗口)
const { app, BrowserWindow } = require("electron");
//监听app的ready事件创建窗口
app.on("ready", () => {
const mainWindow = new BrowserWindow({
width: 1400,
height: 800,
maxWidth: 2000, //resizable为true的情况下 页面最大最小宽高
maxHeight: 1000,
minWidth: 700,
minHeight: 500,
show: false, //窗口是否显示 默认true
frame: true, //窗口是否边框 默认true
resizable: true, //窗口是否可拉伸 默认true
webPreferences: {
nodeIntegration: true, //是否开启支持node 默认false
contextIsolation: false, //是否开启上下文隔离 默认false
},
});
//窗口要加载的本地文件
mainWindow.loadFile("index.html");
// 设置打开窗口的位置
mainWindow.setBounds({ x: 10, y: 10 });
// 设置打开窗口的位置
mainWindow.setPosition(10, 10);
//配合show:false解决加载时出现数秒白屏
mainWindow.once("ready-to-show", () => {
mainWindow.show();
});
//窗口要加载的网页
mainWindow.loadURL(
"https://cdn.jsdelivr.net/gh/kq981024/wkqWarehouse/img/202204111158972.jpeg"
);
//
mainWindow.on('show',()=>{
mainWindow.maximize() //最大化
mainWindow.minimize() //最小化
mainWindow.close() //关闭
})
//监听窗口关闭事件,将窗口设为null释放内存
mainWindow.on("close", () => {
mainWindow = null;
});
});
ipc模块(主进程和渲染进程之间通信)
主进程配置
const { ipcMain } = require("electron");
ipcMain.on("自定义事件名A", (e, data) => {
console.log(data); //获取渲染进程传递的数据
e.reply('自定义事件名B','主进程已接受到,现在是回复') //主进程回复渲染进程
});
渲染进程配置
const { ipcRenderer } = require("electron");
document.querySelector("#btn").addEventListener("click", () => {
ipcRenderer.send("自定义事件名A", "渲染数据"); //传递数据至主进程
});
ipcRenderer.on("自定义事件名B", (e, data) => { //获取主进程传递的数据
console.log(data);
});
remote模块(渲染进程拥有主进程的方法能力)
主进程配置
// 导入remote
const remote = require("@electron/remote/main");
// 初始化remote
remote.initialize();
// 主进程监听ready事件的回调中使用remote
remote.enable(mainWindow.webContents);
渲染进程配置
//导入remore
const { BrowserWindow } = require("@electron/remote");
主进程引入
// 主进程监听ready事件的回调中引入菜单
require("./main/menu.js");
配置
const { Menu } = require("electron");
// 新建菜单模板
let template = [
{
label: "前端基础", //菜单名
// 子菜单数组
submenu: [
{
label: "HTML5",
//子菜单单击事件回调
accelerator: "ctrl+n", //设置快捷键
click: () => {}, //菜单点击回调
},
{ label: "CSS3" },
{ label: "JavaScript" },
],
},
];
// 构建菜单模板
let M = Menu.buildFromTemplate(template);
// 设置菜单
Menu.setApplicationMenu(M);
shell模块(使网页在本地浏览器打开而不是在窗口中,新窗口直接window.open(url)即可)
渲染进程配置
const { shell } = require("electron"); //导入shell模块
let aHref = document.querySelector("#aHref"); //获取dom a链接
window.onload = () => {
aHref.onclick = (e) => {
e.preventDefault(); //阻止默认事件在本窗口打开
let URL = aHref.getAttribute("href"); //获取URL
shell.openExternal(URL); //通过shell模块使用浏览器打开
};
};
dialog模块(模拟原生的系统文件对话框)
const dialog = require("electron").dialog;
const fs = require("fs");
let openBtn = document.querySelector("#openBtn");
let saveBtn = document.querySelector("#saveBtn");
let messageBtn = document.querySelector("#messageBtn");
let notifyBtn = document.querySelector("#notifyBtn");
// 选择文件
openBtn.onclick = () => {
dialog
.showOpenDialog({
title: "请选择文件", //弹出框标题
defaultPath: "test.jpg", //默认路径
filters: [{ name: "img", extensions: ["jpg"] }], //过滤可选的文件后缀
buttonLabel: "自定义打开按钮",
// properties: ["openFile", "openDirectory", "multiSelections"],
})
.then((res) => {
console.log(res.filePaths[0]); //获取选择的文件
})
.catch((err) => {
console.log(err); //打印错误
});
};
// 保存文件
saveBtn.onclick = () => {
dialog
.showSaveDialog({
title: "保存文件", //弹出框标题
})
.then((res) => {
fs.writeFileSync(res.filePath, "写入内容");
})
.catch((err) => {
console.log(err);
});
};
// 弹出对话框
messageBtn.onclick = () => {
dialog
.showMessageBox({
type: "warning", //消息类型
title: "弹出框标题",
message: "弹出框内容",
buttons: ["是", "不是"], //按钮数组
})
.then((res) => {
console.log(res.response); //选择按钮的数组下标
});
};
// 底部通知框
notifyBtn.onclick = () => {
let param = { title: "底部弹出框标题", body: "底部弹出框内容" };
new window.Notification(param.title, param);
};
globalShortcut模块(全局快捷键)
const globalShortcut = electron.globalShortcut; //引入
//const globalShortcut = require('global-shortcut');
//!必须在ready监听回调中使用
app.on("ready", () => {
globalShortcut.register("ctrl+x", () => {
//使用快捷键的回调
});
let judgeRegister = globalShortcut.isRegister('ctrl+e')?'注册成功':'注册失败' //判断快捷键是否注册成功
});
app.on('will-quit', ()=> {
globalShortcut.unregister('ctrl+x'); //注销ctrl+x快捷键
globalShortcut.unregisterAll(); //注销全部快捷键
});
clipboard模块(剪切板复制粘贴)
const { clipboard } = require("electron");
clipboard.writeText('复制'); //复制话到剪切板
clipboard.readText('粘贴') //粘贴剪切板的话
tray模块(系统托盘 添加图标和上下文菜单到系统通知区)
const {Tray,Menu } = require("electron");
let tray = new Tray("icon.png"); //应用图标
tray.setToolTip("小凯录屏"); //鼠标放置文字
//新建菜单
const menu = Menu.buildFromTemplate([
{
label: "退出",
click: () => {
app.exit();
},
},
]);
tray.setContextMenu(menu); //配置图标右击菜单
设置窗口内打开窗口BrowserView
//设置窗口内打开网页样式
const BrowserView = electron.BrowserView;
let view = new BrowserView();
mainWindow.setBrowserView(view); //窗口设置窗内浏览器
view.setBounds({ x: 0, y: 120, width: 1000, height: 680 });//窗口样式
view.webContents.loadURL('https://cn.bing.com/')//窗口加载的文件网页
子窗口向父窗口传递信息
window.opener.postMessage('子窗口向父窗口传递的信息') //可以使用targetOrigin指向父窗口
设置网络是否连接的不同回调
window.addEventListener("online", () => {}); //上网
window.addEventListener("offline", () => {}); //断网