electron开发中的坑以及解决方法

1,271 阅读2分钟

window下使用electron-builder打包后,托盘图标不显示的问题。

在开发环境下托盘图标正常显示,但是打包安装软件后,托盘图标不显示。

  1. 来到打包后的win-unpacked文件,使用cmd运行程序,报错如下,发现无法找到该图片 图片.png
  2. 使用npm全局安装asar包,在win-unpacked\resources下,运行 asar e xx.exe ./test 解压查看打包代码。都没有发现图标图片。说明改图片没有被打包进去。需要对electron-builder进行正确配置
  3. 在electron-builder中新增打包配置。from表示图片在项目中所处位置,to表示打包后存放的位置

图片.png 4. 根据electron-builder的文档显示。to指向的默认打包路径是resources文件夹下,所以根据配置打包后图片的位置录下

图片.png 5. 根据配置修改托盘图标

图片.png electron-builder.extraResources配置说明文档 www.electron.build/configurati…

electron保持dialog弹窗唯一,并且聚焦于dialog

dialog的弹窗api:dialog.showMessageBox([browserWindow, ] options),当传入browserWindow时,dialog弹窗会作为他的子窗口,聚焦并且强制进行窗口操作。

export class TaskEvent {
    static getWin(event) {
        return BrowserWindow.fromWebContents(event.sender); //获取对应的borwerWindow对象
    }
    static listen() {
        ipcMain.handle(TASK_EVENT.SWITCH, async (e) => {
            const win = this.getWin(e)
            const res = dialog.showMessageBoxSync(win, {
                title: '提示',
                message: '事项未完成,是否切换',
                buttons: ['取消', '确定'],
                icon: getIcon() //配置图标路劲
            })
            return res
        })

    }

}

参考文档:electronjs.p2hp.com/docs/latest…

electron常用进程间通信方式

  1. 渲染进程发送到主进程(单项),渲染进程只负责发送信息,主进程只负责接受信息
/*
api:ipcRenderer.send(channel, ...args) 
*/
ipcRenderer.send('test', { title: '提示', message: '专注结束' })

/*
api:ipcMain.on(channel, listener)
*/
ipcMain.on('test', (e, data) => {
    if (!Notification.isSupported()) return false
    new Notification({
        title: data.title, body: data.message, silent: true,
        icon: iconPath
    }).show()
})
  1. 渲染进程和主进程双向通信
/*
api:ipcRenderer.invoke(channel, ...args) return Promise
渲染进程通过invoke向主进程发送数据。本身是个promise,通过then方法拿到主进程返回的值
*/
ipcRenderer.invoke('switch-task',true).then(res => {
    console.log('resss',res)
})

/*
api:ipcMain.handle(channel, listener),listener中的返回值将作为应答值返回给渲染进行,
如果返回一个Promise,会返回Promise的结果
*/
ipcMain.handle('switch-task', (e) => {
    const win = this.getWin(e)
    //showMessageBoxSync 使用同步dialog弹窗,将dialog的结果返回给渲染进程
    const res = dialog.showMessageBoxSync(win, {
            itle: '提示',
            message: '事项未完成,是否切换',
            buttons: ['取消', '确定'],
            })
    return res  //将res返回给渲染进程
})

electron中localStorage的保存位置

C:\Users\UsersName\AppData\Roaming\