main.cjs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. const { app, BrowserWindow, ipcMain } = require('electron')
  2. const path = require('path')
  3. const fs = require('fs')
  4. // 设置环境变量
  5. process.env.NODE_ENV = process.env.NODE_ENV || 'development'
  6. // 命令行参数
  7. const argv = process.argv.slice(2);
  8. // 保存主窗口引用
  9. let mainWindow
  10. // 设置文件路径
  11. const settingsPath = path.join(app.getPath('userData'), 'settings.json');
  12. // 加载设置
  13. function loadSettings() {
  14. try {
  15. if (fs.existsSync(settingsPath)) {
  16. const data = fs.readFileSync(settingsPath, 'utf8');
  17. console.log('读取到设置文件:', data);
  18. try {
  19. return JSON.parse(data);
  20. } catch (parseErr) {
  21. console.error('解析设置文件失败:', parseErr);
  22. }
  23. } else {
  24. console.log('设置文件不存在:', settingsPath);
  25. }
  26. } catch (err) {
  27. console.error('加载设置失败:', err);
  28. }
  29. return { defaultLoad: false };
  30. }
  31. // 保存设置
  32. function saveSettings(settings) {
  33. try {
  34. // 确保目录存在
  35. const settingsDir = path.dirname(settingsPath);
  36. if (!fs.existsSync(settingsDir)) {
  37. fs.mkdirSync(settingsDir, { recursive: true });
  38. }
  39. const data = JSON.stringify(settings, null, 2);
  40. console.log('保存设置:', data, '到路径:', settingsPath);
  41. fs.writeFileSync(settingsPath, data, 'utf8');
  42. return true;
  43. } catch (err) {
  44. console.error('保存设置失败:', err);
  45. return false;
  46. }
  47. }
  48. function createWindow() {
  49. // 加载设置
  50. const settings = loadSettings();
  51. console.log('当前设置:', settings);
  52. // 判断是否直接加载应用
  53. // 命令行参数优先,其次是设置,最后是生产环境默认值
  54. const shouldDirectLoad = argv.includes('--direct-load') ||
  55. settings.defaultLoad === true ||
  56. process.env.NODE_ENV === 'production' ||
  57. process.env.FORCE_DIRECT_LOAD === 'true';
  58. console.log('是否直接加载应用:', shouldDirectLoad,
  59. '(命令行:', argv.includes('--direct-load'),
  60. ', 设置:', settings.defaultLoad,
  61. ', 环境:', process.env.NODE_ENV, ')');
  62. // 创建浏览器窗口
  63. mainWindow = new BrowserWindow({
  64. width: 1200,
  65. height: 800,
  66. webPreferences: {
  67. nodeIntegration: false,
  68. contextIsolation: true,
  69. preload: path.join(__dirname, 'preload.cjs'),
  70. webSecurity: process.env.NODE_ENV === 'production',
  71. devTools: true
  72. }
  73. });
  74. // 添加控制台消息监听
  75. mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
  76. console.log(`[WebContents] ${message}`);
  77. });
  78. // 打开开发者工具
  79. mainWindow.webContents.openDevTools();
  80. if (shouldDirectLoad) {
  81. // 直接加载Vue应用并导航到报表页面
  82. console.log('直接加载报表页面...');
  83. loadVueApp('/report');
  84. } else {
  85. // 加载测试页面
  86. const testPath = path.join(__dirname, 'test.html');
  87. console.log('加载测试页面...');
  88. mainWindow.loadFile(testPath);
  89. }
  90. // 添加错误处理
  91. mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
  92. console.error('页面加载失败:', errorCode, errorDescription);
  93. const testPath = path.join(__dirname, 'test.html');
  94. if (fs.existsSync(testPath)) {
  95. mainWindow.loadFile(testPath);
  96. }
  97. });
  98. // 在加载页面前添加
  99. mainWindow.webContents.on('dom-ready', () => {
  100. console.log('DOM已准备就绪');
  101. });
  102. // 在页面加载后执行脚本
  103. mainWindow.webContents.on('did-finish-load', () => {
  104. console.log('页面加载完成');
  105. });
  106. }
  107. // 当Electron完成初始化并准备创建浏览器窗口时调用此方法
  108. app.whenReady().then(() => {
  109. createWindow()
  110. // 设置IPC监听器
  111. ipcMain.on('load-app', (event, route) => {
  112. console.log('收到加载应用请求, 路由:', route || '默认');
  113. loadVueApp(route);
  114. });
  115. // 添加保存设置的IPC监听器
  116. ipcMain.on('save-settings', (event, settings) => {
  117. console.log('收到保存设置请求:', settings);
  118. const success = saveSettings(settings);
  119. console.log('保存设置结果:', success ? '成功' : '失败');
  120. });
  121. // 添加获取设置的IPC处理器
  122. ipcMain.handle('get-settings', () => {
  123. return loadSettings();
  124. });
  125. app.on('activate', () => {
  126. if (BrowserWindow.getAllWindows().length === 0) {
  127. createWindow()
  128. }
  129. })
  130. })
  131. // 加载Vue应用的函数
  132. function loadVueApp(route) {
  133. if (!mainWindow) return;
  134. const indexPath = path.join(__dirname, '../dist/index.html');
  135. console.log('尝试加载Vue应用:', indexPath);
  136. if (fs.existsSync(indexPath)) {
  137. console.log('Vue应用文件存在,正在加载...');
  138. // 构建URL,如果有指定路由则添加
  139. let url = `file://${indexPath}?t=${Date.now()}`;
  140. if (route) {
  141. url += `#${route}`; // 使用hash模式路由
  142. }
  143. console.log('加载URL:', url);
  144. // 在加载前清除缓存
  145. mainWindow.webContents.session.clearCache().then(() => {
  146. mainWindow.loadURL(url);
  147. // 监听加载完成事件
  148. mainWindow.webContents.once('did-finish-load', () => {
  149. console.log('Vue应用加载完成');
  150. });
  151. });
  152. } else {
  153. console.error('Vue应用文件不存在:', indexPath);
  154. mainWindow.webContents.executeJavaScript(`
  155. alert('Vue应用文件不存在: ${indexPath}');
  156. `).catch(err => console.error('执行脚本失败:', err));
  157. }
  158. }
  159. // 关闭所有窗口时退出应用
  160. app.on('window-all-closed', () => {
  161. if (process.platform !== 'darwin') {
  162. app.quit()
  163. }
  164. })
  165. // 添加全局未捕获异常处理
  166. process.on('uncaughtException', (error) => {
  167. console.error('未捕获的异常:', error)
  168. })