main.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const { app, BrowserWindow, screen, session, ipcMain} = require('electron')
  2. const path = require('path')
  3. let mainWindow;
  4. const createWindow = () => {
  5. // 获取主显示器的尺寸
  6. const primaryDisplay = screen.getPrimaryDisplay()
  7. const { width, height } = primaryDisplay.workAreaSize
  8. mainWindow = new BrowserWindow({
  9. width: width,
  10. height: height,
  11. webPreferences: {
  12. preload: path.join(__dirname, 'preload.js'),
  13. contextIsolation: true,
  14. nodeIntegration: true
  15. }
  16. })
  17. // 将窗口位置设置为(0,0),确保它位于屏幕左上角
  18. mainWindow.setPosition(0, 0)
  19. mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  20. // 添加 'close' 事件监听器
  21. mainWindow.on('close', (event) => {
  22. event.preventDefault(); // 阻止窗口立即关闭
  23. mainWindow.webContents.send('clear-token-cache');
  24. });
  25. }
  26. app.on('ready', () => {
  27. const filter = {urls: ['file:///C:/api/*', 'file:///api/*', 'file:///D:/api/*']};
  28. const url = 'http://127.0.0.1:8014'
  29. //const url = 'http://192.168.0.125:8014'
  30. session.defaultSession.webRequest.onBeforeRequest(filter, (details, callback) => {
  31. const val = details.url
  32. let newUrl = val.replace('file:///api', url);
  33. newUrl = newUrl.replace('file:///C:/api', url);
  34. newUrl = newUrl.replace('file:///D:/api', url);
  35. callback({ redirectURL: newUrl });
  36. });
  37. });
  38. app.whenReady().then(() => {
  39. createWindow()
  40. app.on('activate', () => {
  41. if (BrowserWindow.getAllWindows().length === 0) {
  42. createWindow()
  43. }
  44. })
  45. //下载文件
  46. ipcMain.on('download-file', async (event, url) => {
  47. if (!url) return
  48. const filePath = path.join(app.getPath('downloads'));
  49. const win = BrowserWindow.fromWebContents(event.sender);
  50. win.webContents.downloadURL(url, filePath);
  51. });
  52. // 监听渲染进程发来的缓存清理完成的消息
  53. ipcMain.on('token-cache-cleared', () => {
  54. setTimeout(() => {
  55. if (mainWindow && !mainWindow.isDestroyed()) {
  56. mainWindow.destroy();
  57. }
  58. app.quit();
  59. },500)
  60. });
  61. })
  62. app.on('before-quit', (event) => {
  63. if (mainWindow && !mainWindow.isDestroyed()) {
  64. event.preventDefault();
  65. mainWindow.webContents.send('clear-token-cache');
  66. }
  67. })
  68. app.on('window-all-closed', () => {
  69. if (process.platform !== 'darwin') app.quit();
  70. });
  71. app.on('will-quit', () => {
  72. mainWindow = null;
  73. });