1.新建文件夹electron-demo
2.初始化项目
npm init
3.全局安装electron
npm i electron -s
npm i nodemon -g // 实时刷新
npm i electron-win-state -s // 保存窗口状态
4.配置package.json文件
{
"name": "electron-demo",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "chcp 65001 && nodemon --exec electron . --watch ./ --ext .js,.html,.css"
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^27.0.0",
"electron-win-state": "^1.1.22"
}
}
5.新增main.js入口文件
const path = require('path');
const { app, BrowserWindow, ipcMain, dialog, globalShortcut, Menu, clipboard } = require('electron');
const WinState = require('electron-win-state').default; // 保存窗口状态
const createTray = require("./tray");
const { mainMenu, contextMenu } = require('./menu')
const createWindow = () => {
const winState = new WinState({
defaultWidth: 1000,
defaultHeight: 800
})
const win = new BrowserWindow({
...winState.winOptions,
show: false,
// frame: false,
backgroundColor: '#6435c9',
webPreferences: {
// nodeIntegration: true, // 允许渲染进程访问nodejs(不推荐)
// contextIsolation: false, // 是否开启上下文隔离(不推荐)
preload: path.join(__dirname, './preload.js') //20版本以后不在拥有nodejs的模块
}
})
winState.manage(win);
// 加载远程连接
// win.loadURL("https://www.baidu.com");
// 加载本地文件
win.loadFile('index.html');
// 解决初始化白屏(等到页面加载玩再打开窗口)
win.on('ready-to-show', () => {
win.show();
})
// 定义托盘
createTray(app, win);
// 打开控制台
const wc = win.webContents;
wc.openDevTools();
// wc.on('did-finish-load', () => {
// console.log('did-finish-load 页面里面的资源加载完毕')
// })
// wc.on('dom-ready', () => {
// console.log('dom-ready dom节点加载完毕')
// })
wc.on('context-menu', (e, params) => {
contextMenu.popup();
// console.log('点击右键')
// dialog.showOpenDialog({
// buttonLabel: '选择',
// defaultPath: app.getPath('desktop'),
// properties: ['multiSelections','createDirectory','openFile','openDirectory']
// }).then(res => {
// console.log(res)
// })
})
// 设置快捷键
globalShortcut.register('ctrl + q', () => {
console.log('我是快捷键')
})
Menu.setApplicationMenu(mainMenu);
// 打开子窗口
// const win2 = new BrowserWindow({
// width: 400,
// height: 300,
// parent: win,
// modal: true, // 模态窗口,打开子窗口的时候,不能操作父窗口
// })
// win2.loadURL('https://www.baidu.com')
// 关闭所有警告,不推荐
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllwindows().length === 0) createWindow()
})
});
// 和before-quit只有一个生效
app.on('window-all-closed', () => {
console.log('关闭所有窗口的生命周期')
// 注销快捷键(窗口关闭的时候)
globalShortcut.unregister('ctrl + q');
if (process.platform !== 'darwin') app.quit()
})
// app.on('before-quit', () => {
// console.log('before-quit')
// })
// app.on('browser-window-blur', () => {
// console.log('browser-window-blur')
// })
// app.on('browser-window-focus', () => {
// console.log('browser-window-focus')
// })
// 主进程订阅渲染进程触发的事件
ipcMain.handle('send-event', (event, msg) => {
console.log(7777, msg)
return '来自主进程返回的数据';
})
ipcMain.handle('copy-event', (event, msg) => {
clipboard.writeText(msg);
})
ipcMain.handle('show-event', (event, msg) => {
return clipboard.readText();
})
6.预加载文件(preload.js)
// 预加载(渲染进程, 与主进程进行沟通的桥梁)
const { contextBridge, ipcRenderer, clipboard } = require('electron')
const handSend = async (msg) => {
let call = await ipcRenderer.invoke('send-event', msg)
console.log(6666, call)
}
const copy = (msg) => {
ipcRenderer.invoke('copy-event', msg)
}
const show = async () => {
let msg = await ipcRenderer.invoke('show-event');
console.log(321, msg)
}
// 将数据挂载到window下
contextBridge.exposeInMainWorld('myApi', {
platform: process.platform,
handSend,
copy,
show
})
7.index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 解决警告 -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:;script-src 'self'; style-src 'self' 'unsafe-inline'">
</head>
<body>
hello world
<button id="btn1">渲染进程发送消息到主进程</button>
<button id="btn2">复制</button>
<button id="btn3">黏贴</button>
<img src="https://img0.baidu.com/it/u=56109659,3345510515&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1697648400&t=22ca95e4e119cd4ef23fcd9b54fc6b10" alt="">
<script src="./index.js"></script>
</body>
</html>
8.渲染进程
// 渲染进程
document.getElementById('btn1').addEventListener('click', () => {
myApi.handSend('来自渲染进程的数据123');
})
document.getElementById('btn2').addEventListener('click', () => {
myApi.copy('放到剪切板的数据');
})
document.getElementById('btn3').addEventListener('click', () => {
myApi.show();
})
9.自定义托盘(tray.js)
const { Tray, Menu } = require('electron')
function createTray(app, win) {
const tray = new Tray('icon.ico');
tray.setToolTip('我的应用');
tray.on('click', (e) => {
if (e.shiftKey) {
app.quit();
} else {
// 左键显示隐藏
win.isVisible() ? win.hide() : win.show();
}
})
// 右键菜单
tray.setContextMenu(Menu.buildFromTemplate([
{
label: 'item1'
}
]))
}
module.exports = createTray
10.自定义菜单
const { Menu } = require('electron')
// 主菜单
const mainMenu = Menu.buildFromTemplate([
{
label: '文件',
submenu: [
{
label: '打开'
},
{
label: '另存'
},
{
label: '新建'
},
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{role: 'copy'},
{role: 'paste'},
]
},
{
label: '动作',
submenu: [
{
label: 'DevTools',
role: 'toggleDevTools'
},
{
role: 'toggleFullScreen'
},
{
label: 'Greet',
click: () => {
console.log(123)
}
}
]
}
])
// 右键菜单
const contextMenu = Menu.buildFromTemplate([
{
label: 'test1'
},
{
label: 'test2'
},
{
role: 'editMenu'
}
])
module.exports = {
mainMenu,
contextMenu
}