main.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const fs = require('fs')
  2. const yaml = require('js-yaml')
  3. const { app, BrowserWindow, Menu, dialog } = require('electron')
  4. const { autoUpdater } = require('electron-updater')
  5. const fileContents = fs.readFileSync('resources/app-update.yml', 'utf-8')
  6. const data = yaml.load(fileContents)
  7. const createWindow = () => {
  8. Menu.setApplicationMenu(null)
  9. if (data.url) {
  10. autoUpdater.autoDownload = false
  11. autoUpdater.setFeedURL({
  12. provider: data.provider,
  13. url: data.url
  14. })
  15. // 检查更新出错
  16. autoUpdater.on('error', (err) => {
  17. dialog.showMessageBox({
  18. type: 'error',
  19. title: '错误',
  20. noLink: true,
  21. message: '更新发生错误',
  22. detail: err.message
  23. })
  24. })
  25. // 检测到有版本更新
  26. autoUpdater.on('update-available', (e) => {
  27. dialog.showMessageBox({
  28. type: 'info',
  29. title: '提示',
  30. noLink: true,
  31. message: e.version,
  32. detail: '发现新版本,是否现在下载?',
  33. buttons: ['取消', '下载']
  34. }).then((res) => {
  35. if (res.response === 1) {
  36. autoUpdater.downloadUpdate()
  37. }
  38. })
  39. })
  40. // 更新下载进度事件
  41. autoUpdater.on('download-progress', (progress) => {
  42. // https://www.electronjs.org/zh/docs/latest/tutorial/progress-bar
  43. win.setProgressBar(progress.percent / 100)
  44. })
  45. // 下载完成,询问用户是否更新
  46. autoUpdater.on('update-downloaded', (e) => {
  47. dialog.showMessageBox({
  48. type: 'info',
  49. title: '提示',
  50. noLink: true,
  51. message: e.version,
  52. detail: '已下载新版本,是否关闭应用更新?',
  53. buttons: ['取消', '安装']
  54. }).then((res) => {
  55. if (res.response === 1) {
  56. autoUpdater.quitAndInstall()
  57. } else {
  58. win.setProgressBar(-1)
  59. }
  60. })
  61. })
  62. }
  63. const win = new BrowserWindow({
  64. center: true,
  65. minWidth: 1280,
  66. minHeight: 800,
  67. icon: 'dist/favicon.ico'
  68. })
  69. win.maximize()
  70. win.loadFile('dist/index.html')
  71. win.on('ready-to-show', () => {
  72. autoUpdater.checkForUpdates()
  73. })
  74. }
  75. app.whenReady().then(() => {
  76. createWindow()
  77. })