1.新建文件夾electron-demo
2.初始化項(xiàng)目
npm init
3.全局安裝electron
npm i electron -s
npm i nodemon -g // 實(shí)時(shí)刷新
npm i electron-win-state -s // 保存窗口狀態(tài)
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; // 保存窗口狀態(tài)
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, // 允許渲染進(jìn)程訪問nodejs(不推薦)
// contextIsolation: false, // 是否開啟上下文隔離(不推薦)
preload: path.join(__dirname, './preload.js') //20版本以后不在擁有nodejs的模塊
}
})
winState.manage(win);
// 加載遠(yuǎn)程連接
// win.loadURL("https://www.baidu.com");
// 加載本地文件
win.loadFile('index.html');
// 解決初始化白屏(等到頁面加載玩再打開窗口)
win.on('ready-to-show', () => {
win.show();
})
// 定義托盤
createTray(app, win);
// 打開控制臺(tái)
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節(jié)點(diǎn)加載完畢')
// })
wc.on('context-menu', (e, params) => {
contextMenu.popup();
// console.log('點(diǎn)擊右鍵')
// dialog.showOpenDialog({
// buttonLabel: '選擇',
// defaultPath: app.getPath('desktop'),
// properties: ['multiSelections','createDirectory','openFile','openDirectory']
// }).then(res => {
// console.log(res)
// })
})
// 設(shè)置快捷鍵
globalShortcut.register('ctrl + q', () => {
console.log('我是快捷鍵')
})
Menu.setApplicationMenu(mainMenu);
// 打開子窗口
// const win2 = new BrowserWindow({
// width: 400,
// height: 300,
// parent: win,
// modal: true, // 模態(tài)窗口,打開子窗口的時(shí)候,不能操作父窗口
// })
// win2.loadURL('https://www.baidu.com')
// 關(guān)閉所有警告,不推薦
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllwindows().length === 0) createWindow()
})
});
// 和before-quit只有一個(gè)生效
app.on('window-all-closed', () => {
console.log('關(guān)閉所有窗口的生命周期')
// 注銷快捷鍵(窗口關(guān)閉的時(shí)候)
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')
// })
// 主進(jìn)程訂閱渲染進(jìn)程觸發(fā)的事件
ipcMain.handle('send-event', (event, msg) => {
console.log(7777, msg)
return '來自主進(jìn)程返回的數(shù)據(jù)';
})
ipcMain.handle('copy-event', (event, msg) => {
clipboard.writeText(msg);
})
ipcMain.handle('show-event', (event, msg) => {
return clipboard.readText();
})
6.預(yù)加載文件(preload.js)
// 預(yù)加載(渲染進(jìn)程, 與主進(jìn)程進(jìn)行溝通的橋梁)
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)
}
// 將數(shù)據(jù)掛載到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">渲染進(jìn)程發(fā)送消息到主進(jìn)程</button>
<button id="btn2">復(fù)制</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.渲染進(jìn)程
// 渲染進(jìn)程
document.getElementById('btn1').addEventListener('click', () => {
myApi.handSend('來自渲染進(jìn)程的數(shù)據(jù)123');
})
document.getElementById('btn2').addEventListener('click', () => {
myApi.copy('放到剪切板的數(shù)據(jù)');
})
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('我的應(yīng)用');
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: '動(dòng)作',
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
}