初学Electron

213 阅读1分钟

1.初始化项目

先创建一个目录,进入该目录cmd,输入以下命令

npm init
npm install electron --S 

2. 配置package.json

先安装nodemon,用于实时更新,不需要每次都重启刷新

npm i nodemon --D

"scripts": {
    "start": "nodemon --watch index.js --exec electron .", // 添加这一行,注意最后面有个小点
    "test": "echo \"Error: no test specified\" && exit 1"
  },

3. 目录结构

image.png

4. 代码

index.js

loadURL:通过url加载服务器上的静态资源。可以是 http协议,也可以是 file协议

loadFile:加载本地html文件,会自动在前面添加上 "file://" 协议。 

const { app, BrowserWindow, Tray, Menu } = require('electron')
const path = require('path')
const iconPath = path.join(__dirname, './src/img/icon.png')
let tray

app.on('ready', () => {
    // 创建一个窗口
    const mainWindow = new BrowserWindow({
        // resizable: false,
        width: 800,
        height: 600,
        icon: iconPath, // 图标
        webPreferences: {
            backgroundThrottling: false,
            nodeIntegration: true,
            contextIsolation: false,
            // preload: path.join(__dirname, './preload.js')
        }
    })
     // 使用 remote 模块, 在main.js中就可以调用进程对象的方法
    require('@electron/remote/main').initialize()
    require('@electron/remote/main').enable(mainWindow.webContents)
    //渲染文件 
    mainWindow.loadURL(`file://${__dirname}/src/main.html`)

    // 托盘
    tray = new Tray(iconPath)
    tray.setToolTip('Lny')
    // 点击托盘显示隐藏
    tray.on('click', () => {
        if (mainWindow.isVisible()) {
            mainWindow.hide()
        } else {
            mainWindow.show()
        }
    })
    // 右键菜单
    tray.on('right-click', () => {
        const menuConfig = Menu.buildFromTemplate([
            {
                label: '退出',
                click: () => app.quit()
            }
        ])
        tray.popUpContextMenu(menuConfig)
    })
})

5. 点击按钮跳转到新窗口

main.js

const { BrowserWindow } = require('@electron/remote')
const btn = document.getElementById('btn')

btn.onclick = () => {
    let newWindow = new BrowserWindow({
        width: 800,
        height: 600
    })
    newWindow.loadURL(`file://${__dirname}/newPage.html`)
    newWindow.on('close', () => {
        newWindow = null
    })
}

6. 启动命令

npm run start

7. 自定义菜单

(1)新建menu.js
// 1. 导入electron的 Menu
const { Menu } = require('electron')

// 2. 创建菜单模块,数组里每一个对象都是一个菜单
const template = [
    {
        label: '选项一',
        // 下一级菜单
        submenu: [
            {
                label: '选项一(1)',
                // 添加快捷键
                accelerator: 'ctrl+n'
            },
            { label: '选项一(2)' },
            { label: '选项一(3)' },
            { label: '选项一(4)' }
        ]
    },
    {
        label: '选项二',
        // 下一级菜单
        submenu: [
            { label: '选项二(1)' },
            { label: '选项二(2)' },
            { label: '选项二(3)' }
        ]
    }
]

// 3. 从模版中创建菜单
const myMenu = Menu.buildFromTemplate(template)

// 4. 设置为应用程序菜单
Menu.setApplicationMenu(myMenu)
(2)在index.js中引入
require('./src/js/menu')