Electron桌面客户端美化笔记
美化内容
1.Electron自定义窗口标题栏
2.为标题栏增加图标,放大,刷新,关闭功能按钮(涉及主进程和渲染进程通信)
3.鼠标右键新增自定义菜单按钮
Electron自定义窗口标题栏
我们知道Electron窗口可直接加载网页连接(比如百度),打包后即可安装(exe即桌面程序),所以很多网站做好web端的同时,可能需要提供一个可安装执行的桌面程序,使得用户觉得更直观(有安装图标,点击即运行),而无需打开浏览器,点击连接或则输入网址访问。
但是Electron自带标题栏样式很不美观,我们往往需要自定义顶部标题栏已符合我们自己的程序。这就需要自定义标题栏,需要以下几个步骤:
- 去掉原生标题栏 ,将原生标题栏取消或隐藏调,在main.js中进行窗口配置
const WIDTH = 1550
const HEIGHT = 900
let mainWindow
let winConfig = {
width: WIDTH,
transparent: false,//修改,否则窗口放大没法恢复
height: HEIGHT,
show: false,
resizable: true,
fullscreenable: true,
maximizable: true,
titleBarStyle: 'hidden', //启用自定义标题栏
frame: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
// 2. Enable Node.js integration
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
webSecurity: false, //禁用同源策略
webviewTag: true,
allowRunningInsecureContent: true,
plugins: true,
show: false
},
icon: path.join(__dirname, "./public/icon.ico")
}
mainWindow = new BrowserWindow(winConfig)
- mainWindow = new BrowserWindow(winConfig)传入winConfig
- 新增本地html文件index.html,index文件分为两个部分,即顶部标题栏,和以下的内容区,标题栏用于替换窗体原生的标题栏,内容区则用于加载网页地址;
- 特别注意加载内容区使用webview而非iframe 这样很多功能在后续的实现中会非常方便比如刷新,前进后退等;
顶部标题栏(本地index.html中)根据自己的css随意适配,只需要注意点击事件和触发流程,如上图代码(仅举例一个关闭按钮),那么如何调用ectron关闭窗口功能呢
当点击右上角关闭按钮时候,closeWindow()调用,只需要 ipcRenderer.send(“closeWindow”);发送一个消息即可
在index.html script节点中添加
const {ipcRenderer} = require(‘electron’)即可使用
同时发送消息需要主进程事先注册消息监听,即在main.js中事先注册,注意事件关键字closeWindow“要和发送消息相匹配,同理 main.js中引入ipcMain即可使用
const {ipcMain} = require(“electron”)
ipcMain.on('closeWindow', async (event) => {
console.log("closeWindow,关闭组件进程并关闭窗口")
killThirdPartyWidgets().then(() => {
if (mainWindow) {
mainWindow.close()
}
})
})
这样就实现了一个简单的关闭窗口功能,调用window.close()方法
鼠标右键新增自定义菜单按钮
Menu, , MenuItem 同上ipcMain引入:
Menu.setApplicationMenu(null);
const menu = new Menu();
menu.append(new MenuItem({
label: ‘刷新’, click: function (event) {
mainWindow.webContents.send(“onRefreshWebPage”, “刷新webview”);
}
}))
app.on(“web-contents-created”, (…[/* event */, webContents]) => {
//Webview is being shown here as a window type
webContents.on(“context-menu”, (event, click) => {
event.preventDefault();
menu.popup(webContents);
}, false);
});
需要在index.html中事先监听事件onRefreshWebPage
//onRefresh
ipcRenderer.on(‘onRefreshWebPage’, (event, data) => {
reloadPage()
})
reloadPage 即为webview 刷新api