electron入门简单使用

cfn
2020-12-08
477

开发环境

我的版本 node和npm 版本

微信截图_20201208154139.png

electron的安装

npm init -y
npm i --save-dev electron

创建入口文件

微信截图_20201208154139.png

写入

const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('./src/main/index.html') } app.whenReady().then(createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } })

win.loadFile(’./src/main/index.html’)
就是打开要显示的页面

创建第一个页面

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body style="background: white;"> <h1>Hello World!</h1> <p> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </p> </body> </html>

一些配置

const { app, BrowserWindow, Menu, dialog, Tray, net } = require('electron') let tray; function createWindow () { let win = new BrowserWindow({ width: 420, height: 600, webPreferences: { nodeIntegration: true }, // 禁止修改窗口大小 resizable: false }) // 托盘显示 tray = new Tray('./static/app.ico') const contextMenu = Menu.buildFromTemplate([ { label: '显示桌面', click: function () {win.show()}}, { label: '直接退出', click: function (){app.exit()}} ]) tray.setToolTip('国家条码信息查询') tray.setContextMenu(contextMenu) tray.on("click",(e)=>{ win.show() }) // Menu.setApplicationMenu(null) win.loadFile('./src/main/index.html') // win.hide() // 显示调试窗口 win.webContents.openDevTools({mode:'detach'}) // 关闭拦截 win.on("close", (e) => { e.preventDefault(); win.hide() // dialog.showMessageBox({ // type: 'warning', // title: '关闭提醒', // message: '程序即将退出', // buttons: ['退出程序', '托盘挂机'], // noLink: true // }).then((res) => { // if (res.response === 0) app.exit() // else win.hide() // }) }) }
评论 1