electron
创建应用项目
https://www.electronforge.io/
npm init electron-app@latest jjsg
运行1
npm run start
运行2
npx electron .
设置窗口
https://www.electronjs.org/zh/docs/latest/tutorial/window-customization
mainWindow = new BrowserWindow({
minWidth: 1334,
minHeight: 750,
width: 1334,
height: 750,
fullscreen: isPackaged, // 启动就全屏
fullscreenable: true, // 是否能全屏
autoHideMenuBar: isPackaged, // 隐藏菜单栏
// resizable: false, // 能否缩放
webPreferences: {
preload: path.join(__dirname, 'web/preload.js'),
},
icon: path.join(__dirname, 'icon/app_logo.png')
});
设置ICON
forge.config.js
module.exports = {
packagerConfig: {
"icon": "src/icon/app_logo",
"asar": true,
overwrite: true,
}
}
mainWindow = new BrowserWindow({
icon: path.join(__dirname, 'icon/app_logo.png')
});
设置环境路径
[app | Electron (electronjs.org)](https://www.electronjs.org/zh/docs/latest/api/app#appgetapppath) |
app.getAppPath()
[app | Electron (electronjs.org)](https://www.electronjs.org/zh/docs/latest/api/app#appgetpathname) |
[app | Electron (electronjs.org)](https://www.electronjs.org/zh/docs/latest/api/app#appsetpathname-path) |
app.setPath(name, path)
app.getPath(name)
进程通信
https://www.electronjs.org/zh/docs/latest/tutorial/ipc
资源下载
https://www.electronjs.org/zh/docs/latest/api/session#sesdownloadurlurl
ipcMain.on(AppWebAPI.downloadURL, (event, url) => {
event.sender.session.downloadURL(url);
});
https://www.electronjs.org/zh/docs/latest/api/session#event-will-download
https://www.electronjs.org/zh/docs/latest/api/download-item
// 监听资源下载
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
// 无需对话框提示, 直接将文件保存到路径
var url = item.getURL();
var savePath = path.join(app.getPath('downloads'), item.getFilename());
item.setSavePath(savePath);
item.on('updated', (event, state) => {
if (state === 'interrupted') {
mainWindow.webContents.send(AppWebAPI.event_downloadURL_interrupted, url);
console.log('Download is interrupted but can be resumed')
} else if (state === 'progressing') {
mainWindow.webContents.send(AppWebAPI.event_downloadURL_progressing, url, item.getReceivedBytes(), item.getTotalBytes(), Math.floor(item.getReceivedBytes() / item.getTotalBytes() * 100));
if (item.isPaused()) {
console.log('Download is paused')
} else {
console.log(`Received bytes: ${item.getReceivedBytes()} / ${item.getTotalBytes()}, ${Math.floor(item.getReceivedBytes() / item.getTotalBytes() * 100)}%`)
}
}
})
item.once('done', (event, state) => {
mainWindow.webContents.send(AppWebAPI.event_downloadURL_done, url, state);
if (state === 'completed') {
console.log('Download successfully');
// 下载完成,打开
var extname = path.extname(savePath).toLowerCase();
if (extname == '.exe') {
// 执行exe
shell.openExternal(savePath);
}
else {
// 显示所在文件夹
shell.showItemInFolder(savePath);
}
} else {
console.log(`Download failed: ${state}`)
}
});
});
// end --- 'will-download'